何が起こっているのか理解できますか?私はもちろんの ステートメントを使用する際に変数とSQL Serverを使用する
を
- SAQAのIDを取得しようとしているが、私は理解していないものがあります。
私は私のクエリで変数を作成した場合など
public Int32 T_Course_Id = 0, T_Company_Id = 0, T_Nqf = 0, T_Credit = 0; string queryTaskId = "SELECT [course_saqa_id] FROM"+ "[sta].[dbo].[Courses]"+ "WHERE course_name = '" + _Coursename + "'"; string queryNqf = "SELECT [course_nqf]"+ "FROM [sta].[dbo].[Courses]"+ "WHERE course_saqa_id = '" + T_Course_Id + "'"; using (SqlConnection Conn = new SqlConnection(ConnString)) { Conn.Open(); using (SqlCommand command = new SqlCommand(queryTaskId, Conn)) { using (SqlDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { reader.Read(); // Call Read before accessing data. T_Course_Id = reader.GetInt32(0); } // Call Close when done reading. reader.Close(); } } using (SqlCommand command = new SqlCommand(queryCredit, Conn)) { using (SqlDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { reader.Read(); // Call Read before accessing data. T_Credit = reader.GetInt32(0); } // Call Close when done reading. reader.Close(); } } Conn.Close(); }
私は
T_Credit
変数の0値を得るが、私は(このようにそれを行う場合にのみ、最後で、このようにそれを行うと一部)あなたは、私が代わりに変数
の直接SQLコマンドを渡している見ることができるようにusing (SqlCommand command = new SqlCommand("SELECT [course_nqf] FROM [sta].[dbo].[Courses] WHERE course_saqa_id = '" + T_Course_Id + "'", Conn))
using (SqlCommand command = new SqlCommand("SELECT [course_nqf] FROM [sta].[dbo].[Courses] WHERE course_saqa_id = '" + T_Course_Id + "'", Conn)) { using (SqlDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { reader.Read(); // Call Read before accessing data. T_Credit = reader.GetInt32(0); } // Call Close when done reading. reader.Close(); } }
、私は、正しい値を取得します
ここで変数が動作しないのはなぜですか?
は、テンプレート文字列を使用してみましたか? C#6 また、 'using(){...}'スタイルを使用しているときにcloseを呼び出すのはなぜですか? –
これはちょうどタイプミスで、最初のケースでは間違った変数を使用しています。 'queryCredit'の代わりに' queryNqf'を使うべきです。 – Alisson
[SQLインジェクション警告](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29。aspx) - あなたはSQLステートメントを連結しない** ** SQLインジェクションを避けるため**代わりに**パラメータ化されたクエリを使用する - [Little Bobby Tables](https://xkcd.com/327/)をチェックしてください –