错误:SQL语法中存在错误 - 但SQL语句有效

时间:2014-04-23 09:41:34

标签: c# mysql sql

我试图在for循环中迭代地更新我的c#app中的MySql表。我收到了这个错误:

 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '935 WHERE ID=1' at line 1

但是,当我在PhpMyAdmin中运行我的SQL语句时,它运行良好,它会更新我表中的特定位置。

CODE:

for (int i = 1; i <= 10; i++)
        {
            string queryMean = " SELECT (RT1+RT2+RT3+RT4+RT5+RT6+RT7+RT8+RT9+RT10+RT11+RT12+RT13+RT14+RT15+RT16+RT17+RT18+RT19+RT20+RT21+RT22+RT23+RT24+RT25+RT26+RT27+RT28+RT29+RT30+RT31+RT32+RT33+RT34+RT35+RT36+RT37+RT38+RT39+RT40+RT41+RT42+RT43+RT44+RT45+RT46+RT47+RT48+RT49+RT50+RT51+RT52+RT53+RT54+RT55+RT56+RT57+RT58+RT59+RT60+RT61+RT62+RT63+RT64+RT65+RT66+RT67+RT68+RT69+RT70+RT71+RT72+RT73+RT74+RT75+RT76+RT77)/77 AS priem FROM reflextime WHERE reflextime.ID=" + i;
            MySqlCommand cmd = new MySqlCommand(queryMean, conect);

            readerMean = cmd.ExecuteReader();
            readerMean.Read();
            string result = readerMean["priem"].ToString();
            double priem = Convert.ToDouble(result);
            double priemer = Math.Round(priem, 3);
            readerMean.Close();

            string query2 = "UPDATE feture SET priemer="+priemer+" WHERE ID="+i;
            MySqlCommand cmdx = new MySqlCommand(query2, conect);
            cmdx.ExecuteScalar();   // here is the exception thrown
        }

谢谢。

1 个答案:

答案 0 :(得分:1)

请注意,如果在您的计算机上运行(斯洛伐克文化设置),则double priemer中的值会转换为字符串,例如&#34; 586935&#34 ;.这不是你想要的,因为,在SQL中的含义与.不同。 解决问题的最简单方法是使用

string query2 = "UPDATE feture SET priemer="+priemer.ToString(CultureInfo.InvariantCulture)+" WHERE ID="+i;

顺便说一句,如果你在发布之前打印了query2,那么你可能已经发现了这个问题。

还要注意,这绝不是在C#中调用查询的最佳实践,可以找到如何创建参数化查询的好线索here