如何从数据库中保存变量并在C#中使用它?

时间:2015-05-12 09:36:22

标签: c# database

我正在更改程序,我需要一些帮助,因为我不知道C#。我改变了:

strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID=385";
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();

有一种情况我需要找到一个ID,存储它然后再使用它。所以我使用select

 OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE    Type=1", db_def.conn);
 OleDbDataReader reader = cmd.ExecuteReader();
 if (reader.HasRows)
 {
   reader.Read();
   var result = reader.GetInt32(0);
 }

 strSQL = "UPDATE materials SET ";
 strSQL = strSQL + "Dscr = 'concrete', ";
 strSQL = strSQL + "width=50 ";
 strSQL = strSQL + " WHERE ID=result";
 objCmd = new OleDbCommand(strSQL, db_def.conn);
 objCmd.ExecuteNonQuery();

但是我收到了一个错误:

  

没有给出一个或多个必需参数的值。

2 个答案:

答案 0 :(得分:0)

虽然您正在处理的代码不太理想,但我现在只提供您需要的修补程序:

将您的代码更改为:

 OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE    Type=1", db_def.conn);
 OleDbDataReader reader = cmd.ExecuteReader();

int result=0;

 if (reader.HasRows)
 {
   reader.Read();
   result = reader.GetInt32(0);
 }

 strSQL = "UPDATE materials SET ";
 strSQL = strSQL + "Dscr = 'concrete', ";
 strSQL = strSQL + "width=50 ";
 strSQL = strSQL + " WHERE ID=" + result;
 objCmd = new OleDbCommand(strSQL, db_def.conn);
 objCmd.ExecuteNonQuery();

您需要在SQL字符串之外提供结果变量的值 - 数据库不会在其自己的上下文中知道“结果”的值。

编辑:result变量在if语句中声明,因此无法进一步分配。

答案 1 :(得分:0)

你可以尝试这个并告诉我它是否有效

('12', ' in class', '1', ' has got a score of', 0)

('as', ' in class', '1', ' has got a score of', 1)

('lars', ' in class', '1', ' has got a score of', 7, ' with a time of', 39.79597997665405)

('lars', ' in class', '1', ' has got a score of', 8)

('lars', ' in class', '1', ' has got a score of', 8)

('lars', ' in class', '1', ' has got a score of', 8)

('lars2', ' in class', '1', ' has got a score of', 1)

('test', ' in class', '1', ' has got a score of', 1, ' with a time of', 17)