如何在ASP.net上解决System.Data.SqlClient.SqlException错误?

时间:2017-12-30 09:06:06

标签: c# mysql asp.net

我正在做一个涉及将数据添加到现有数据库行的Web应用程序,在我的情况下我想要它,当我点击一个按钮时,数据将插入到具有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.'

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

这是我对按钮的代码:

    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不允许我上传图片以便更好地说明,对不起

2 个答案:

答案 0 :(得分:0)

尝试使用'初始目录'而不是像你这样的连接字符串中的AttachDbFilename:

RelativeLayout

答案 1 :(得分:0)

由于它是SQL数据库,您的连接字符串应该看起来像......

Data Source =。\ SQLEXPRESS; Database =; Integrated Security = True

这将引用sql server实例并找到你提到的数据库     “您的数据库名称”

还想参考数据库的完整路径!! 查看此现有帖子:A database with the same name exists, or specified file cannot be opened, or it is located on UNC share

相关问题