c# - 无法插入数据库但未产生错误
问题描述
没有将数据插入数据库并且没有出现任何错误
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
应该相同,- 确保您的语法正确。
让我知道您是否还有顾虑。
推荐阅读
- java - 如何在 AWS Lambda 转换后将事件放回 Kinesis Firehose?
- python - 如何在熊猫中创建嵌套数据框
- c - 使用 mkdir 过程 AS400/IBMi 在 IFS 中创建目录
- javascript - 添加离子日期时间前缀和后缀
- ios - 首选项:iPhone/iPad 上快捷方式应用中 Instagram 设置的根 URL
- c - 内核 C++ 中的鼠标驱动程序,如何创建和使用它?
- java - 是否有在 2 个线程(1 个读取器 - 1 个写入器)之间同步访问 Map 的最佳方法
- signalr - 带有 asp.net 核心集线器的 SignalR 服务
- mockito - 在单元测试期间制作 mockito 以使用真正的 Log4j
- r - 编辑数据表单元格值后立即更改单元格的颜色 R闪亮