c# - 如何使用插入查询将组合框项目保存在数据库中?

标签 c# database

我想使用组合框将帐户保存在登录数据库中。

当我尝试保存时,出现错误:“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/

相关文章:

c# - 底层连接已关闭 : The server committed a protocol violation. FTP

.net - 用于开发目的的数据库服务器

c# - Visual Studio 2017 封装字段 - 如何恢复旧格式?

c# - 为什么 GetHashCode 在 Object 类中?

c# - 如何从网站下载 .EXE 文件?

c# - 富文本框追加查询 C#

mysql - 如何从ms sql迁移到mysql

database - 是否建议在 Oracle 表空间中使用统一的扩展区大小?

mysql - SQL对整个表的非空约束

c# - 在用 C++ 编写的 COM 客户端中抛出空返回值异常