winforms 我创建了一个windows窗体并将其连接到数据库,但运行时出现错误

c2e8gylq  于 2022-12-14  发布在  Windows
关注(0)|答案(1)|浏览(150)

我在Visual Application中创建了一个Windows窗体,并将其连接到SQL Server数据库。但是,当我运行下面所示的代码时,出现了一个错误:
异常(0x80131904):INSERT语句中的列数多于VALUES子句中指定的值。VALUES子句中的值数必须与INSERT语句中指定的列数相匹配。)
编码:

private void button1_Click (object sender, EventArgs e)
{
    connection.Open();

    SqlCommand cmd = connection.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "INSERT INTO [MyTable] (Name, Surename, Address) VALUES ('"+ textBox1.Text +","+ textBox2.Text + "," + textBox3.Text + "')";

    cmd.ExecuteNonQuery();
    connection.Close();

    textBox1.Text = "";
    textBox2.Text = "";
    textBox3.Text = "";
    textBox4.Text = "";
}

我试着删除一些值并运行它。但它再次显示相同的错误。

ee7vknir

ee7vknir1#

我建议

  • 将数据操作放入类中,从窗体调用
  • 通过Add而不是AddWithValue而不是字符串连接使用参数
  • 不要对所有操作使用一个连接,但这是您的选择。

下面是返回新主键的示例。

public class DataOperations
{
    private static string _connectionString = "TODO";

    public static int Insert(string name, string surName, string address)
    {
        using (var cn = new SqlConnection(_connectionString))
        {
            using var cmd = new SqlCommand
            {
                Connection = cn,
                CommandText = "INSERT INTO [MyTable] (Name, Surename, Address) VALUES (@Name, @SurName, @Address);" +
                              "SELECT CAST(scope_identity() AS int);"
            };

            cmd.Parameters.Add("@Name", SqlDbType.NChar).Value = name;
            cmd.Parameters.Add("@SurName", SqlDbType.NChar).Value = surName;
            cmd.Parameters.Add("@Address", SqlDbType.NChar).Value = address;

            cn.Open();

            return Convert.ToInt32(cmd.ExecuteScalar());
        }
    }
}

而此示例插入一条记录,类似于您现在所做的操作。

public class DataOperations
{
    private static string _connectionString = "TODO";

        public static void Insert(string name, string surName, string address)
        {
            using (var cn = new SqlConnection(_connectionString))
            {
                using var cmd = new SqlCommand
                {
                    Connection = cn,
                    CommandText = "INSERT INTO [MyTable] (Name, Surename, Address) VALUES (@Name, @SurName, @Address);"
                };

                cmd.Parameters.Add("@Name", SqlDbType.NChar).Value = name;
                cmd.Parameters.Add("@SurName", SqlDbType.NChar).Value = surName;
                cmd.Parameters.Add("@Address", SqlDbType.NChar).Value = address;

                cn.Open();

                cmd.ExecuteNonQuery();
            }
        }
}

相关问题