C# 无效的列名';a';

C# 无效的列名';a';,c#,mysql,C#,Mysql,我有一个贯穿始终的查询,如果输入的代码与表中找到的代码匹配,则应该提取用户的姓名和电子邮件地址。代码是另一个表上的主键,也是名称和电子邮件表上的外键。但是,每当我运行查询时,它都会返回无效的列名“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 Cours

我有一个贯穿始终的查询,如果输入的代码与表中找到的代码匹配,则应该提取用户的姓名和电子邮件地址。代码是另一个表上的主键,也是名称和电子邮件表上的外键。但是,每当我运行查询时,它都会返回无效的列名“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();

您可能需要在sql语句中添加一个引号,如

string sql = "select * from SI where Course = '" + course + "'";

但是,您现在使用的方式也容易受到SQL注入的影响。理想情况下,您可以使用sql参数执行它。

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();

使用参数而不是字符串连接来避免注入攻击-想象一下
课程
的值将是
''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();
            }
        }
    }
}

您的列是否为nvarchar?这是您应该使用参数而不是将值连接到SQL的原因之一。另一种是SQL注入攻击。