【问题标题】:C# Form not inserting values into SQL Server databaseC# 表单未将值插入 SQL Server 数据库
【发布时间】:2013-04-06 18:07:18
【问题描述】:

我有一个简单的创建一个新用户表单,它从两个文本框中获取值,用户名和密码。 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();
    }

【问题讨论】:

    标签: c# sql-server winforms insert sqlconnection


    【解决方案1】:

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

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

    在我看来,真正的解决方案

    1. 安装 SQL Server Express(反正你已经完成了)

    2. 安装 SQL Server Management Studio Express

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

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

      Data Source=.\\SQLEXPRESS;Database=DebenhamsProjectOfficeDatabase;Integrated Security=True
      

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

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

    【讨论】:

    • 非常感谢您的建议,我将尝试这个,为我是新手 c# 程序员的天真道歉。非常感谢。
    • catch (Exception) 是另一种有缺陷的方法。
    【解决方案2】:

    您必须调用Command.ExecuteNonQuery() 才能使insert 语句生效。

    try
    {
          SqlCommand command = new SqlCommand(sqlquery, cn);
          command.Parameters.AddWithValue("Username", username);
          command.Parameters.AddWithValue("Password", password);
          command.ExecuteNonQuery();
          command.Parameters.Clear();
          MessageBox.Show("User Added");
    }
    catch (Exception ex)
    {
          MessageBox.Show(ex.Message);
    }
    

    【讨论】:

      【解决方案3】:

      只是尝试修复代码。有些元素很重要,有些元素只是优雅。 试试看,它可能会起作用。或者可以指出错误所在:

      private void button2_Click(object sender, EventArgs e)
          {
              string username = txtUsername.Text;
              string password = txtPassword.Text;
              string sqlquery;
      
              //Put away the apostrophes and used twice double quotations for
              //the full path of the database file:
              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);
      
              /* Better to let the program fail than think it's open and moving on
              removed try, catch*/
              cn.Open();
      
      
              //Why using your TextBoxes values if you already created strings?
              //changed
      
              //you should also be careful users can't type something like "') in the      
              //textboxes or they may cause a SQL injection
      
              sqlquery = "INSERT INTO Users (Username, Password) VALUES ('" + username + "','" + password + "')";
      
              try
              {
                  SqlCommand command = new SqlCommand(sqlquery, cn);
                  /* unnecessary since you already built a query command.Parameters.AddWithValue("Username", username);
                  command.Parameters.AddWithValue("Password", password);
                  command.Parameters.Clear();   */
      
                  //Missing!!
                  command.ExecuteNonQuery();
                  MessageBox.Show("User Added");
              }
              catch (Exception ex)
              {
                  MessageBox.Show(ex.Message);
              }
      
              //Elegance
              txtUsername.Clear();
              txtPassword.Clear();
              cn.Close();
          }
      

      【讨论】:

      • 非常感谢您花时间解决此问题。现在可以了!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多