且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-29 08:41:37

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

Just trying a code fix. Some elements are crucial, some are just elegant. Try it, it might work., or could point to where the error is:

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:UsersNickDocumentsVisual Studio 2010ProjectsDebenhamsProjectOffice V.01DebenhamsProjectOffice V.01DebenhamsProjectOfficeDatabase.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();
    }