如果输入的代码与表中找到的代码匹配,我有一个贯穿的查询,并且应该提取用户的姓名和电子邮件地址。代码是另一个表上的主键,是名称和电子邮件表上的外键。但是,每当我运行查询时,它都会返回无效的列名称' a'。
// the variable course runs through a method to capture the
// code from a textbox the user enters it in.
string sql = "select * from SI where Course= " + course;
SqlCommand command = new SqlCommand(sql, connection.con);
SqlDataReader read = command.ExecuteReader();
if (read.Read())
{
siname = read["Name"].ToString();
siemail = read["Email"].ToString();
}
read.Close();
答案 0 :(得分:4)
使用参数代替字符串连接以避免注入攻击 - 假设course
的值为'' GO DROP TABLE SI GO
。
另一件事是使用using
语句。一旦代码超出范围,这将释放未使用的连接和内存。
string command= "select * from SI where Course = @course";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(command, connection))
{
cmd.Parameters.Add("@course", SqlDbType.VarChar).Value = course;
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (read.Read())
{
siname = read["Name"].ToString();
siemail = read["Email"].ToString();
}
}
}
}
答案 1 :(得分:0)
Ben Chan打败了我。问题可能没有使用''围绕用户输入。我还建议在sql命令中使用参数,防止SQL注入并使其看起来更好。而不是
string sql = "select * from SI where Course= '" + course + "'";
你可以使用:
string sql = "select * from SI where Course = @course";
完整代码:
// the variable course runs through a method to capture the
// code from a textbox the user enters it in.
string sql = "select * from SI where Course = @course";
SqlCommand command = new SqlCommand(sql, connection.con);
command.Parameters.AddWithValue("@course", course);
SqlDataReader read = command.ExecuteReader();
if (read.Read())
{
siname = read["Name"].ToString();
siemail = read["Email"].ToString();
}
read.Close();
答案 2 :(得分:-1)
您可能需要在sql语句中添加单引号,如
string sql = "select * from SI where Course = '" + course + "'";
但是,您现在拥有它的方式也容易受到SQL注入的影响。理想情况下,您可以使用sql参数执行它。