使用存储在变量中的值更新数据库

问题描述:

我正在使用 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