你应该user
用括号括起来[]
string strSQL = string.Format("Select * From [User] where UserId = '{0}'",user);
上面的查询容易受到SQL Injection
. 应该对其进行参数化以避免这种情况。下面是一个例子:
string user = "1234";
string strSQL = "Select * From [User] where UserId = @userID";
SqlCommand myCommand = new SqlCommand(strSQL, cnn);
myCommand.AddWithValue("@userID", user);
reader = myCommand.ExecuteReader();
使用以下
Try-Catch
阻止正确捕获错误
using
正确处置物品的声明
片段:
string user = "1234";
string strSQL = "Select * From [User] where UserId = @userID";
using (SqlConnection cnn = new SqlConnection("connection string here"))
{
using (SqlCommand myCommand = new SqlCommand(strSQL, cnn))
{
myCommand.Parameters.AddWithValue("@userID", user);
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["columnName"].ToString());
}
}
}
}