这是我的代码
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = @"Data Source=|DataDirectory|\Database_POS.sdf";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText= "INSERT INTO Customer (Email) Values (@email);";
command.Parameters.AddWithValue("@email",textBox_Email.Text);
connection.Open();
command.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
这是我的设计
I am only trying to save 'email' here.
这是我的 sql 表,问题是我什至无法将单个字段保存到表中。
数据库设计
现在错误是这个
最佳答案
一些要检查的东西:
您遇到错误了吗?如果是,错误是什么?请注意,您正在将错误消息写入控制台窗口,但您的应用程序是 Windows 应用程序。您的应用程序是否有控制台窗口?如果不是,请检查 Visual Studio 中的“输出”窗口。或者更简单,使用
MessageBox.Show
来显示错误。如果程序运行没有任何错误,请检查
command.ExecuteNonQuery()
的返回值。它告诉您有多少条记录受到影响。如果大于零,则该值确实存储在数据库中。确保您在程序中看到了要插入的数据库文件的内容!您可能已经从项目目录中打开了
Database_POS.sdf
,但程序将数据插入到“bin\Debug”目录中的另一个Database_POS.sdf
。
-- 更多帮助--
将您的方法更改为:
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = @"Data Source=|DataDirectory|\Database_POS.sdf";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText= "INSERT INTO Customer (Email) Values (@email);";
command.Parameters.AddWithValue("@email",textBox_Email.Text);
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
if(rowsAffected > 0)
MessageBox.Show("Data inserted successfully");
else
MessageBox.Show("Nothing inserted into the database!");
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show(ex.ToString()); // for debugging purpose
}
}
关于c# - 无法保存数据 c# Windows 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20113515/