使用存储在变量中的值更新数据库 [英] Updating the database using the value which is stored in variable
本文介绍了使用存储在变量中的值更新数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Visual C# 2010 express windows 窗体应用程序 &用于数据库的 MySQL.我想从 DB 获取一个值(当前的学生人数)并将其增加 1 并更新该值.为此,我使用了下面的代码,但我收到一个错误,名为'字段列表'中的未知列'x'.
I'm using Visual C# 2010 express windows form application & Mysql for DB. I want to get a value (current no of students) from DB and increase it by 1 and update that value. for that I use the below code, but I'm getting an error called "unknown column 'x' in 'field list'.
connection.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT NoOfStudents FROM batch", connection);
MySqlDataReader dr = null;
dr = cmd1.ExecuteReader();
int x;
while (dr.Read())
{
x = Convert.ToInt32(dr[0]);
x = x + 1;
}
dr.Close();
MySqlCommand cmd2 = new MySqlCommand("UPDATE batch SET NoOfStudents= x", connection);
cmd2.ExecuteNonQuery();
connection.Close();
推荐答案
试试这个
string sql=string.Format("UPDATE batch SET NoOfStudents= {0}",x);
MySqlCommand cmd2 = new MySqlCommand(sql, connection);
x 是在你的程序中声明的一个变量,Mysql 对此一无所知,这只是一个字符串,它的内容被编译器忽略
x is a variable declared in your program and Mysql dont know any thing about it, this is just a string and its content is ignored by the compiler
这篇关于使用存储在变量中的值更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文