C# 数据库问题

本文关键字:问题 数据库 | 更新日期: 2023-09-27 18:32:25

有人可以告诉我为什么这不将值添加到数据库中吗?表单运行良好,不返回任何错误。

    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection connection = new SqlConnection();
        SqlCommand command = new SqlCommand();
        connection.ConnectionString = (@"Data Source=.'SQLEXPRESS;AttachDbFilename=C:'Users'John'Documents'Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
        command.Parameters.AddWithValue("@userName", textBox1.Text);
        command.Parameters.AddWithValue("@passWord", textBox2.Text);
        command.CommandText = "INSERT INTO Setup (userName, password) VALUES(@userName, @passWord)";

        try
        {
            connection.Open();
            int rowsAffected = command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            // handle exception
        }
        finally
        {
            connection.Close();
        }

    }

仅供参考:我是"新手",我的数据库称为设置。我手动添加了一个名为 myTable 的表,其中包含 2 列用户名和另一列名为密码的表,均设置为 nchar(50)

C# 数据库问题

您需要指定Table,而不是数据库(在连接字符串中使用)。 将架构前缀添加到表名称中:

command.CommandText = "INSERT INTO dbo.myTable (userName, password) VALUES (@userName, @passWord)";

并添加:

command.Connection = connection;

Command对象与连接对象关联。

您的代码应如下所示:

  • 设置连接对象。
  • 如@LarsTech所述指定表名。
  • 在指定表名(如 [Schema name].[Table Name] )时,最佳做法是使用两部分表示法。因此,您必须指定表名,例如dbo.MyTable

代码片段

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = (@"Data Source=.'SQLEXPRESS;AttachDbFilename=C:'Users'John'Documents'Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;");
    SqlCommand command = new SqlCommand();
    command.Connection = connection;
    command.CommandText = "INSERT INTO dbo.MyTable  (userName, password) VALUES (@userName, @passWord)";
    command.Parameters.AddWithValue("@userName", textBox1.Text);
    command.Parameters.AddWithValue("@passWord", textBox2.Text);
    try
    {
        connection.Open();
        int rowsAffected = command.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        //handle exception
    }
    finally
    {
        connection.Close();
    }
}

表单运行良好,不返回任何错误。

那可能是因为你正在吞下它们。摆脱(或记录)您的catch (Exception ex)

通常,.NET BCL 设计良好 - 如果某个方法不起作用,则会出现异常。

[现在]我有错误"执行非查询:连接属性尚未初始化"。

右。您需要将SqlConnection传递给SqlCommand

SqlCommand command = new SqlCommand();
command.Connection = connection;