C# 无法插入数据库,但未产生错误

C# 无法插入数据库,但未产生错误,c#,sql,database,insert,C#,Sql,Database,Insert,未将数据插入数据库且未收到任何错误 private void add_Click(object sender, EventArgs e) { SqlConnection connection = new SqlConnection(global::Employees.Properties.Settings.Default.Database1ConnectionString); try { stri

未将数据插入数据库且未收到任何错误

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();
        }

}

尝试这种方法将如预期的那样工作

               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();

                }
注意:

  • 检查连接字符串上的数据库名称
  • 表名和给定参数(例如
    @username
    )应相同
  • 确保语法正确

  • 如果您还有其他问题,请告诉我。

    您遇到了什么错误?问题是什么?请澄清您面临的问题。可能您插入了错误的数据库?我没有看到任何错误,并且在输入数据库时,添加的数据没有appear@HusseinMohamed. . . 尝试调试肯定会有帮助。如果您在SQL server中执行相同的查询,它是否插入?除了使用
    语句
    之外,它与他的答案有什么不同,因为他无法指定错误。我已经用我的示例测试了他的代码,并按预期工作。这就是为什么将其作为答案发布。你可以试试。这个答案一点帮助都没有。它不执行相同的查询。缺少要插入的值的一半。这是否决投票的有效原因吗?我已经给他让路了!OP没有提到他的错误!我认为第二句话不正确。。。您可以根据需要命名参数;它们不必与字段名对应。