Where子句抛出错误

时间:2015-10-25 15:05:57

标签: c# mysql sql

为什么此代码会抛出错误?

using (MySqlConnection cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
{
    {
        MySqlCommand Command = new MySqlCommand();
        Command.Connection = cn;

        Command.CommandText = "UPDATE TeleworksStats SET Ja= ('" + JaTak +
            "') WHERE Brugernavn = " + VarribleKeeper.Brugernavn + "' AND Dato = " +
            DateTime.Today.ToString("yyyy-MM-dd") + "";
        cn.Open();
        Command.ExecuteNonQuery();
        //Ryd op
        Command.Dispose();
        cn.Close();
    }
}

2 个答案:

答案 0 :(得分:3)

您在'Brugernavn =后错过了一个引用Dato

Brugernavn = "... '" + VarribleKeeper.Brugernavn + "' AND Dato = '" +
             DateTime.Today.ToString("yyyy-MM-dd") + "'";

另外,我强烈建议您始终使用parameterized queries来避免SQL Injection这样:

Command.CommandText =
     "UPDATE TeleworksStats SET Ja = @Ja WHERE Brugernavn = @Brugernavn and ...";
Command.Parameters.AddWithValue("@Ja", JaTak);
Command.Parameters.AddWithValue("@Brugernavn",  VarribleKeeper.Brugernavn);

虽然直接指定类型并且使用Value属性比AddWithValue更好。检查一下:Can we stop using AddWithValue() already?

答案 1 :(得分:3)

我认为您还有更多需要注意的事项,而不是忘记'Brugernavn列的值和Dato列的单引号,我认为您还需要记住更多内容。

using(var cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
using(var Command = cn.CreateCommand())
{
   Command.CommandText = @"UPDATE TeleworksStats SET Ja = @Ja 
                           WHERE Brugernavn = @Brugernavn  AND Dato = @Dato";
   Command.Parameters.Add("@Ja", MySqlDbType.VarChar).Value = JaTak;
   Command.Parameters.Add("@Ja", MySqlDbType.VarChar).Value = VarribleKeeper.Brugernavn;
   Command.Parameters.Add("@Ja", MySqlDbType.DateTime).Value = DateTime.Today;
   // I assumed your column types. You should write proper column types instead.

   cn.Open();
   Command.ExecuteNonQuery();
}