c# - 如何解决 ASP.net 上的 System.Data.SqlClient.SqlException 错误?

标签 c# mysql asp.net

我正在做一个网络应用程序,涉及将数据添加到现有数据库行中,在我的例子中,我希望当我单击按钮时,数据被插入到具有 NULL 值的列中。

我有一个页面,允许用户选择参加旅行的日期和人数,当他们单击“立即预订”按钮时,日期和人员数据应添加到数据库中。

但是,当我单击该按钮时,此错误显示为:

System.Data.SqlClient.SqlException: 'An attempt to attach an auto-named database for file C: \Users\xxx\Documents\xxx\Project\App_Data\Database.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.'

我的 friend 说,要解决这个错误,我需要删除当前的数据库并再次重做整个数据库,但我发现这非常耗时且乏味,因为我已经建立了一个大数据库。

这些是我的按钮代码:

    protected void bookBtn_Click(object sender, EventArgs e)
     {
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\xxx\Documents\XXX\Project\App_Data\Database.mdf;Integrated Security=True");
    //SqlCommand cmd = new SqlCommand("Booking",con);
    //not sure if this is correct
    SqlCommand cmd = new SqlCommand("Update Tours set date = + '"+dateTextbox.Text+"', person = '"+personDLL.Text+"' Where tourName=@tourName");
    cmd.CommandType = System.Data.CommandType.StoredProcedure;

    cmd.Parameters.AddWithValue("date", dateTextbox.Text);
    cmd.Parameters.AddWithValue("person", personDLL.Text);




    con.Open(); //error here
    int k = cmd.ExecuteNonQuery();
    if (k != 0)
    {
       lblmsg.Text = "Record Inserted Succesfully into the Database";
       lblmsg.ForeColor = System.Drawing.Color.CornflowerBlue;
    }
    con.Close();

 }

有什么方法可以解决以下错误,而无需重做整个数据库?

*我只有一个数据库,没有重复的

*由于我没有 10 个声誉,stackOverflow 不允许我上传图像以获得更好的说明,对此感到抱歉

最佳答案

尝试在连接字符串中使用“初始目录”而不是 AttachDbFilename,如下所示:

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=C: \Users\g_jes\Documents\Gilberte Jessie\aspjProject\App_Data\Database.mdf;Integrated Security=True");

关于c# - 如何解决 ASP.net 上的 System.Data.SqlClient.SqlException 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48032475/

相关文章:

c# - ASP :RequiredFieldValidator does not validate hidden fields

mysql - 未分类产品查询

mysql 我们可以在不更改最大数据包大小的情况下更改最大默认 JSON 列长度吗?

php - 如何获取所有记录并在右侧显示信息。取决于数据库中的值

javascript - 单击确认消息框中的取消按钮后如何清除文本框?

c# - WPF 中使用 SkiaSharp 实现模糊文本

c# - WPF .NET4.0 重用相同的 UserControl 实例

c# - 如何增加整个应用程序的字体大小(C#)

jquery - 将样式应用于 ASP.NET RadioButtonList

c# - 嵌套的 gridview 获取父行