C# 表单未将值插入 SQL Server 数据库

Nic*_*kB6 2 c# sql-server sqlconnection insert winforms

我有一个简单的创建一个新的用户表单,它从两个文本框中获取值,用户名和密码。button2 单击事件应该采用这些值并将它们插入到数据库中的用户表中。但是,当我运行我的代码时,消息框似乎说数据已添加,我无法使用 VS2010 在数据库中看到数据。

请参阅 VS 中数据库连接的屏幕截图。我还在 VS 中创建了数据库的数据源。

有任何想法吗?

非常感激。

private void button2_Click(object sender, EventArgs e)
    {
        string username = txtUsername.Text;
        string password = txtPassword.Text;
        string sqlquery;
        string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename='C:\Users\Nick\Documents\Visual Studio 2010\Projects\DebenhamsProjectOffice V.01\DebenhamsProjectOffice V.01\DebenhamsProjectOfficeDatabase.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
        SqlConnection cn = new SqlConnection(connection);
        try
        {
            cn.Open();
        }
        catch (Exception)
        {
            MessageBox.Show("Unable to connect to Database");
        }

        sqlquery = "INSERT INTO Users (Username, Password) VALUES ('" + txtUsername.Text + "','" + txtPassword.Text + "')";
        try
        {
            SqlCommand command = new SqlCommand(sqlquery, cn);
            command.Parameters.AddWithValue("Username", username);
            command.Parameters.AddWithValue("Password", password);
            command.Parameters.Clear();
            MessageBox.Show("User Added");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        txtUsername.Text = "";
        txtPassword.Text = "";
        cn.Close();
    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

mar*_*c_s 5

整个User Instance 和 AttachDbFileName=方法是有缺陷的 - 充其量!在 Visual Studio 中运行您的应用程序时,它将复制.mdf文件(从您的App_Data目录到输出目录 - 通常.\bin\debug- 您的应用程序运行的位置),并且很可能,您的INSERT工作正常 - 但您只是查看了错误的 . mdf文件到底!

如果您想坚持使用这种方法,请尝试在myConnection.Close()调用上设置断点- 然后.mdf使用 SQL Server Mgmt Studio Express检查文件 - 我几乎可以肯定您的数据在那里。

真正的解决办法在我看来,将

  1. 安装 SQL Server Express(无论如何你已经完成了)

  2. 安装 SQL Server Management Studio Express

  3. SSMS Express 中创建您的数据库,给它一个逻辑名称(例如DebenhamsProjectOfficeDatabase

  4. 使用其逻辑数据库名称(在服务器上创建时给出)连接到它- 不要乱用物理数据库文件和用户实例。在这种情况下,您的连接字符串将类似于:

    Data Source=.\\SQLEXPRESS;Database=DebenhamsProjectOfficeDatabase;Integrated Security=True
    
    Run Code Online (Sandbox Code Playgroud)

    其他一切都和以前完全一样......

另外:您应该始终使用参数化查询,而不是将您的 SQL 语句连接在一起(尤其是当包含用户输入时!)以 (a) 避免 SQL 注入攻击的任何危险,以及 (b) 提高​​性能!