UPDATE语句应该如何包含多个列, 那个必须更新? (因为一行已经改变了很多内容)
我在这个主板上尝试了一些搜索,但在其他问题中,有时候“[]”围绕着列,有时候没有,但两个版本在我的代码中都不起作用。
这是代码:
try
{
string name = mtb_Name.Text.ToString();
string altname = mtb_AltName.Text.ToString();
string licht = cb_Licht.SelectedItem.ToString();
string boden = cb_Boden.SelectedItem.ToString();
string haerte = cb_Haerte.SelectedItem.ToString();
string pg = cb_PG.SelectedItem.ToString();
string hoehe = mtb_Hoehe.Text.ToString();
string form = cb_Form.SelectedItem.ToString();
string zuechter = cb_Zuechter.SelectedItem.ToString();
string land = cb_Land.SelectedItem.ToString();
string gruppe = cb_Gruppe.SelectedItem.ToString();
//the connection works, I can add stuff in other tables and delete stuff everywhere
parent.GetDBConnection().Open();
OleDbCommand Query = new OleDbCommand();
Query.Connection = parent.GetDBConnection();
Query.Parameters.Clear();
//I build this string at the moment for testing purposes only and
//converted everything and putted in a string to be sure.
//later it will be replaced with the Parameters.Add(,)
//I also did test it with [AltNameRose] as columname instead of AltNameRose
//or wrote instead of the ' ' a "\"" around the strings,
//but doesn´t seem to be the problem.
Query.CommandText = "UPDATE tb_Rose SET" +
" ,AltNameRose = '" + altname +
"' ,NameZuechter = '" + haerte +
"' ,Boden = '" + boden +
"' ,Wuchshoehe = '" + hoehe +
"' ,Farbe = '" + " " +
"' ,Foto = '" + " " +
"' ,Licht = '" + licht +
"' ,Preisgruppe = '" + pg +
"' ,Gruppe = '" + gruppe +
" WHERE NameRose = '" + name + "'";
//the CommandText seems to be missing something, but I don´t know what.
MessageBox.Show(Query.CommandText.ToString());
Query.ExecuteNonQuery();
parent.GetDBConnection().Close();
MessageBox.Show("Rose successfully edited.");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
parent.GetDBConnection().Close();
}
抛出的异常是
UPDATE-Command中的语法错误
表tb_Rose看起来像这样: NameRose | AltNameRose | NameZuechter | Frosthaerte |博登| Wuchshoehe | FARBE |图片|| Licht的| Preisgruppe | GRUPPE
另一个问题是,订单, 我如何通过列也很重要, 但这对我没用。
有人提出错误的小提示吗?
答案 0 :(得分:2)
在第一列之前,您不需要使用逗号 。这就是你的原因;
" ,AltNameRose = '"
应该是
" AltNameRose = '"
但更重要的是,您应该始终使用parameterized queries。这种字符串连接对SQL Injection攻击开放。
还可以使用using
statement自动处理您的连接和命令,而不是手动调用.Close()
方法。
答案 1 :(得分:0)
Update语句的语法是
Update table_name SET
column_name = value,
column_name = value,
....
Where condition
在您的查询中,您在SET关键字后面添加了,
。
在SET关键字后面有,
..尝试下面的代码
Query.CommandText = "UPDATE tb_Rose SET" +
" AltNameRose = '" + altname +
"' ,NameZuechter = '" + haerte +
"' ,Boden = '" + boden +
"' ,Wuchshoehe = '" + hoehe +
"' ,Farbe = '" + " " +
"' ,Foto = '" + " " +
"' ,Licht = '" + licht +
"' ,Preisgruppe = '" + pg +
"' ,Gruppe = '" + gruppe +
" WHERE NameRose = '" + name + "'";