首页 > 解决方案 > 无法插入数据库但未产生错误

问题描述

没有将数据插入数据库并且没有出现任何错误

private void add_Click(object sender, EventArgs e)
{
        SqlConnection connection = new SqlConnection(global::Employees.Properties.Settings.Default.Database1ConnectionString); 
        try
        {             
            string query = "INSERT INTO Employee (username,password,city,phone)";
            query += " VALUES (@username,@password,@city,@phone)";

            SqlCommand myCommand = new SqlCommand(query, connection);
            myCommand.Parameters.AddWithValue("@username", username.Text);
            myCommand.Parameters.AddWithValue("@password", password.Text);
            myCommand.Parameters.AddWithValue("@city", listBox.Text);
            myCommand.Parameters.AddWithValue("@phone", phone.Text);
            connection.Open();
            myCommand.ExecuteNonQuery();

            MessageBox.Show("Success add Employee");
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally{
            connection.Close();
        }

}

标签: c#sqldatabaseinsert

解决方案


尝试这种方式将按预期工作

               string connectionString = @"data source=WS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";//Replace Your connection string


                using (var _connection = new SqlConnection(connectionString))
                {
                    _connection.Open();
                    using (SqlCommand command = new SqlCommand("INSERT INTO Employee (username,password,city,phone)  VALUES (@username,@password,@city,@phone)", _connection))
                    {
                        command.Parameters.AddWithValue("@username", "testuser");
                        command.Parameters.AddWithValue("@password", "pass");
                        command.Parameters.AddWithValue("@city", "TestCity");
                        command.Parameters.AddWithValue("@phone", "TestPhone");
                        SqlDataReader sqlDataReader = command.ExecuteReader();
                        sqlDataReader.Close();
                    }

                    _connection.Close();

                }

笔记:

  1. 检查连接字符串上的数据库名称,
  2. 例如,表名和给定参数@username应该相同,
  3. 确保您的语法正确。

让我知道您是否还有顾虑。


推荐阅读