下面是使用datagridview将值插入到mysql数据库中的代码。 但是,selectcommand正在工作。它没有发生,因为我得到错误,指出“列'用户名'不能为空”。如何在C#中使用MYSQL插入,删除,选择,更新datagridview中的值
如果我使用ms访问数据库,则不会弹出此错误。 任何人都可以帮助我解决这个问题。有没有其他方法可以这样做。
private void button1_Click(object sender, EventArgs e)
{ //Even using functions we can easily update the datagridview
//Select_function();
try
{ //The container which displays the details.
dataGridView1.Visible = true;
//The binding object which binds the datagridview with backend.
BindingSource bs = new BindingSource();
//The datatable through which data is exported to datagridview
table = new DataTable();
bs.DataSource = table;
this.dataGridView1.DataSource = bs;
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s = "select *from user";
cmd = new MySqlCommand(s, conn);
da = new MySqlDataAdapter();
da.SelectCommand = new MySqlCommand(s, conn);
//There is issue in below sytax of insert command.
MySqlCommand insertcommand = new MySqlCommand("insert into user(username,password) values(@username ,@password)", conn);
insertcommand.Parameters.Add("username",MySqlDbType.VarChar,50,"username");
insertcommand.Parameters.Add("password", MySqlDbType.VarChar, 50, "password");
da.InsertCommand = insertcommand;
//Demonstrates update command
MySqlCommand updatecommand = new MySqlCommand("update user set [email protected],[email protected] where ([email protected])", conn);
updatecommand.Parameters.Add("@username", MySqlDbType.VarChar, 50, "username");
updatecommand.Parameters.Add("@password", MySqlDbType.VarChar, 50, "password");
da.UpdateCommand = updatecommand;
//Demonstration of delete Command
MySqlCommand deletecommand = new MySqlCommand("delete from user where [email protected]", conn);
deletecommand.Parameters.Add("@username", MySqlDbType.VarChar, 50, "username");
da.DeleteCommand = deletecommand;
da.Fill(table);
conn.Close();
}
catch (Exception err) { MessageBox.Show(err.Message); }
}
private void button2_Click(object sender, EventArgs e)
{ da.Update(table);
}
嘿感谢您的答案。你绝对正确。这只是一个小的语法错误。 – 2009-10-05 11:06:44
你有没有试过这两个例子?他们都好吗? – Nils 2009-10-05 11:12:56
“:”生成错误。 “?”工作正常。第二个代码片段不会工作。 – 2009-10-05 11:30:29