【发布时间】:2017-08-29 10:55:40
【问题描述】:
有人可以帮助我了解发生了什么吗?我正在尝试获取
- SAQA ID
- NQF 级别
- 学分
当然,但有些东西我不明白。
如果我用我的查询创建一个变量,例如
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 值,但如果我这样做(这只是最后一部分)
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();
}
}
然后我得到正确的值,你可以看到我直接传递 SQL 命令而不是变量
using (SqlCommand command = new SqlCommand("SELECT [course_nqf] FROM [sta].[dbo].[Courses] WHERE course_saqa_id = '" + T_Course_Id + "'", Conn))
为什么变量在这里不起作用?
【问题讨论】:
-
您是否尝试过使用模板字符串? C# 6 此外,当你已经在使用
using() { ... }样式时,为什么还要调用 close ? -
看起来这只是一个错字,您在第一种情况下使用了错误的变量。您应该使用
queryNqf而不是queryCredit。 -
SQL Injection alert - 您应该不将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入 - 查看Little Bobby Tables
-
如果您像这样将 SQL 语句连接在一起,在关键字之间留一些 空格 也会很有帮助.....例如使用
"SELECT [course_saqa_id] FROM " + "[sta].[dbo].[Courses]" + " WHERE course_name = @CourseName";- 注意FROM之后和WHERE关键字之前的SPACE ....