2

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

在此处输入图像描述

4

3 回答 3

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
    

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

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

于 2013-04-06T18:09:06.500 回答
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);
}
于 2013-04-06T18:08:55.013 回答
1

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

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();
    }
于 2013-04-06T19:15:34.943 回答