简体   繁体   English

无法在C#sql数据库中插入数据

[英]Unable to insert data in C# sql database

So when my form loads, it will connect to the database, and when i click on the button, it will insert an new row into my database, but i after i clicked it i didnt see any changes in my table. 所以当我的表单加载时,它将连接到数据库,当我点击按钮时,它会在我的数据库中插入一个新行,但是在我点击它后我没有看到我的表中的任何更改。

namespace database
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SqlConnection con;

        private void Form1_Load(object sender, EventArgs e)
        {
            con = new SqlConnection();
            con.ConnectionString =
              "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\myworkers.mdf;Integrated Security=True;User Instance=True";
            con.Open();
            MessageBox.Show("OPEN!");
        }

        private void label1_Click(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int x;
            SqlCommand thiscommand = con.CreateCommand();
            thiscommand.CommandText =
              "INSERT INTO player_info (player_id, player_name) values (10, 'Alex') ";

            x =  thiscommand.ExecuteNonQuery();  /* I used variable x to verify
                                                    that how many rows are
                                                    affect, and the return is 1.
                                                    The problem is that I don't
                                                    see any changes in my table*/
            MessageBox.Show(x.ToString());
            con.Close();
        }
    }
}

You are using an attached Db file. 您正在使用附加的Db文件。 That means that a Project-build makes a copy in the Bin folder, and you are dealing with 2 different versions of the Db. 这意味着Project-build在Bin文件夹中创建一个副本,并且您正在处理两个不同版本的Db。 You are probably checking in the original. 你可能正在检查原件。

This can actually be quite useful (fresh copy every time). 这实际上非常有用(每次都是新的副本)。 If not, change the Copy-when property of the Db file. 如果没有,请更改Db文件的Copy-when属性。

There's not enough detail to know exactly why the value is not showing up in your database, but I would suggest that you change your coding practice (described below), re-test, and then provide as much detail as you can about exactly where things are failing. 没有足够的细节来确切知道为什么数值没有显示在您的数据库中,但我建议您更改编码实践(如下所述),重新测试,然后尽可能详细地提供关于事物的确切位置失败了。

Coding Practice 编码实践

You open your connection much earlier than you need to (which means you hold a valuable resource longer than necessary) and you do not clean up the connection or the command. 您可以比您需要的更早地打开连接(这意味着您拥有的宝贵资源超过了必要的时间),并且您不会清除连接或命令。 They implement IDisposable, so you must call Dispose() on them. 它们实现了IDisposable,因此您必须在它们上调用Dispose()。 The easiest way to do that is with a using statement. 最简单的方法是使用using语句。

Suggested rewrite: 建议重写:

// Remove initialization of the SqlConnection in the form load event.

private void button1_Click(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection())
    {
        con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\myworkers.mdf;Integrated Security=True;User Instance=True";
        con.Open();
        // Optional: MessageBox.Show("OPEN!");
        int x;
        using (SqlCommand thiscommand = con.CreateCommand())
        {
            thiscommand.CommandText = "INSERT INTO player_info (player_id, player_name) values (10, 'Alex') ";

            x = thiscommand.ExecuteNonQuery();        /*I used variable x to verify that how many rows are affect, and the return is 1. The problem is that i dont see any changes in my table*/
            // Optional: MessageBox.Show(x.ToString());
        }
    }
}

The ExecuteNonQuery method is explained as follows on MSDN: ExecuteNonQuery方法在MSDN上解释如下:

Executes a Transact-SQL statement against the connection and returns
the number of rows affected.

If you get 1 as return value, one record must have been inserted. 如果返回值为1 ,则必须插入一条记录。

Have you forgotten to requery the table? 你忘了重新问上桌吗? The new record will not be displayed automatically in your application. 新记录不会自动显示在您的应用程序中。

You could consider running SQL Profiler to see what is actually being sent to your database. 您可以考虑运行SQL事件探查器以查看实际发送到您的数据库的内容。 You can capture the SQL and then try executing that code directly against the database. 您可以捕获SQL,然后尝试直接对数据库执行该代码。

"player_id" implies this is a primary key if that's the case the insert would fail. “player_id”意味着如果插入失败则这是主键。

I would also recommend changing your approach, as others have, to the "using" style as this will manage your resources for you and make sure you do not leave connections "hanging around". 我还建议像其他人一样改变你的方法,以“使用”的方式,因为这将为你管理你的资源,并确保你不会留下连接“闲逛”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM