c# - 无法保存数据 c# Windows 应用程序

标签 c# database windows

这是我的代码

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

这是我的设计

enter image description here

    I am only trying to save 'email' here. 

这是我的 sql 表,问题是我什至无法将单个字段保存到表中。

enter image description here

数据库设计 enter image description here

现在错误是这个

enter image description here

最佳答案

一些要检查的东西:

  1. 您遇到错误了吗?如果是,错误是什么?请注意,您正在将错误消息写入控制台窗口,但您的应用程序是 Windows 应用程序。您的应用程序是否有控制台窗口?如果不是,请检查 Visual Studio 中的“输出”窗口。或者更简单,使用 MessageBox.Show 来显示错误。

  2. 如果程序运行没有任何错误,请检查 command.ExecuteNonQuery() 的返回值。它告诉您有多少条记录受到影响。如果大于零,则该值确实存储在数据库中。

  3. 确保您在程序中看到了要插入的数据库文件的内容!您可能已经从项目目录中打开了 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/

相关文章:

C#如何将IEnumerable匿名列表转换成数据表

php - 基本 PHP 注册/登录系统

c# - 为什么我的 WPF 应用程序不显示?

C#、SQL Server - 锁定表行读取,根据需要进行编辑并释放锁定

c# - 输出的时候发现currentId不是预期的10000。为什么?如何纠正

database - Oracle 11g JDBC 预取键

mysql - 如何在 MySQL 中创建复合自引用外键?

windows - 是否可以使用 start 从 cmd 文件使用输出重定向?

windows - 使用xcopy复制所有desktop.ini

c# - xml 对象中缺少信封标记