0

所以我有一个 C# 软件,可以将数据保存到我的数据库中,但是每次我运行我的程序并尝试保存数据时,我都会收到此消息,请帮忙?

在此处输入图像描述

try
{
    SqlConnection cnn = new SqlConnection(@"Data  Source=.\SQLEXPRESS;
        AttachDbFilename=C:\Users\Hp\Documents\Visual Studio 2010\Projects\Bank_System\Bank_System\Bank_System.sdf;
        Integrated Security=True;User Instance=True");
    cnn.Open();
    SqlCommand cmd1 = 
       new SqlCommand("insert into user values('" + 
           textBox6.Text + "','" + textBox1.Text + "','" + textBox4.Text + "'," + 
           textBox3.Text + ",'" + textBox2.Text +  "','" + textBox5.Text + "')",
           cnn);
    SqlDataReader dr1 = cmd1.ExecuteReader();
    dr1.Close();
    MessageBox.Show(" Record inserted ", " information inserted");
    cnn.Close();
}
catch (SqlException ex)
{
    MessageBox.Show(ex.Message);
}
4

2 回答 2

0

您正在使用 SDF 文件。此文件适用于 SQL Server Compact,而不适用于 SQL Server Express(或完整)。

在这种情况下,连接字符串应该很简单:

 @"Data Source=<fullpath_and file_to_your_sdf_file>;Persist Security Info=False;"

请注意,在 C# 中,您需要在包含特殊字符(如反斜杠)的字符串前面添加逐字字符

使用 Sql Server Compact 需要安装Microsoft 下载所需的库并使用正确的类。因此,删除 SqlConnection 和 SqlCommand 类并使用 SqlCeConnection 和 SqlCeCommand(等等,用于您的应用程序中使用的其他数据客户端类)。

当然 SqlCeConnection 类可以理解这种不同的连接字符串语法并允许使用 SDF 文件

就是说,请修改构建 sql 命令的代码。像您的代码那样使用字符串连接是一种安全的错误方法。从解析错误(字符串中的引号会破坏语法)到更严重的错误,如Sql Injections

这可能是一种使用参数化查询的方法......

try
{
    string cmdText = "insert into user values(@p1, @p2, @p3,@p4,@p5,@p6)";
    using(SqlCeConnection cnn = new SqlCeConnection(@"Data Source=C:\Users\Hp\Documents\Visual Studio 2010\Projects\Bank_System\Bank_System\Bank_System.sdf;Integrated Security=True"))
    using(SqlCeCommand cmd1 = new SqlCeCommand(cmdText, cnn))
    {
        cnn.Open();
        cmd.Parameters.AddWithValue("@p1", textBox6.Text);
        cmd.Parameters.AddWithValue("@p2", textBox1.Text);
        cmd.Parameters.AddWithValue("@p3", textBox4.Text);
        cmd.Parameters.AddWithValue("@p4", textBox3.Text);
        cmd.Parameters.AddWithValue("@p5", textBox2.Text);
        cmd.Parameters.AddWithValue("@p6", textBox5.Text);
        cmd1.ExecuteNonQuery();
        MessageBox.Show(" Record inserted ", " information inserted");
     }
}
catch (SqlException ex)
{
    MessageBox.Show(ex.Message);
}
于 2014-05-17T09:33:08.113 回答
0

将您的数据库 Bank_System.sdf 复制到 \bin\debug\ 文件夹中,并像这样更改连接字符串:

SqlConnection cnn = new SqlConnection("Data Source=" +@".\SQLEXPRESS;
            AttachDbFilename=Bank_System.sdf;
            Integrated Security=True;User Instance=True");

它应该可以工作,如果发生错误,请尝试从位于 \bin\debug\ 文件夹中的 yourapp.exe 执行您的应用程序

于 2014-05-17T08:51:01.800 回答