有人可以帮助我了解发生了什么吗?我正在尝试获取
- SAQA 编号
- 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))
为什么变量在这里不起作用?
最佳答案
操作顺序很重要。
在您的第一个示例中:
您正在设置 T_Course_ID = 0
的值,然后立即创建一个查询字符串。那时,T_Course_ID
值被评估为 0
并被遗忘。每次使用时都不会评估字符串连接。仅在分配时。
在你的第二个例子中:
T_Course_ID
由您的初始查找分配了一个新值。由于 SQLCommand
是在变量重新分配之后执行的,因此每次都使用新值对其进行评估。
这里是一个使用javascript的例子,同样适用于:
var T_Course_Id = 0;
var queryNqf =
"SELECT [course_nqf]" +
"FROM [sta].[dbo].[Courses]" +
"WHERE course_saqa_id = '" + T_Course_Id + "'";
// Query displays initialized value
console.log(queryNqf);
// Variable is changed
T_Course_Id = 'I Will NOT CHANGE';
// Try to log the updated value but it doesn't work because queryNqf was assigned too early
console.log(queryNqf);
// Reassign with the new value
queryNqf =
"SELECT [course_nqf]" +
"FROM [sta].[dbo].[Courses]" +
"WHERE course_saqa_id = '" + T_Course_Id + "'";
// Retrieve the expect result.
console.log(queryNqf);
关于c# - 在 using 语句中使用变量与 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45937313/