我想使用组合框将帐户保存在登录数据库中。
当我尝试保存时,出现错误:“INSERT INTO 语句中的语法错误”。我试图在我的 INSERT INTO 语句中找到错误,但我无法找出问题所在。这是我用来在组合框中添加项目的代码:
cmbAccountType2.DropDownStyle = ComboBoxStyle.DropDownList;
string str = null;
str = "User";
cmbAccountType2.Items.Add(str);
str = "Administrator";
cmbAccountType2.Items.Add(str);
这是我用来将帐户保存在我的登录数据库中的查询:
private void btnSaveAccount_Click_1(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Do you want to save item?", "Confirmation", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
string q = "INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "', , '" + cmbAccountType2.Text.ToString() + "')";
doSomething(q);
}
else if (result == DialogResult.No)
{
MessageBox.Show("Transaction cancelled.", "Information");
textClear();
}
loadData();
}
最佳答案
这里多了一个逗号
"INSERT INTO LoginDB (userName, password, accountType) VALUES ('" + txtUserName1.Text.ToString() + "', '" + txtPassword1.Text.ToString() + "'**, ,** '" + cmbAccountType2.Text.ToString() + "')";
这是错误的原因,但是您可以在代码中改进一些其他方面,
using (var cmd = new SqlCommand("INSERT INTO LoginDB (userName, password, accountType) VALUES(@name,@pw,@accType)",yourConnection))
{
cmd.Parameters.AddWithValue("name", txtUserName1.Text);
cmd.Parameters.AddWithValue("pw", txtPassword1.Text);
cmd.Parameters.AddWithValue("accType", cmbAccountType2.Text);
cmd.ExecuteNonQuery();
}
- 使用parametirized查询
- 不要使用多余的ToString()方法
关于c# - 如何使用插入查询将组合框项目保存在数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20602483/