【问题标题】:How do I solve System.Data.SqlClient.SqlException error on ASP.net?如何解决 ASP.net 上的 System.Data.SqlClient.SqlException 错误?
【发布时间】:2017-12-30 18:16:21
【问题描述】:

我正在做一个涉及将数据添加到现有数据库行中的 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 不允许我上传图片以获得更好的说明,对此感到抱歉

【问题讨论】:

  • 为什么C:\Users\g_jes\...中的C:后面有空格?
  • 如果我删除空间会有错误,数据库无法执行。我在@maddy23285 之前尝试过这个

标签: c# mysql asp.net


【解决方案1】:

尝试在连接字符串中使用“初始目录”而不是 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");

【讨论】:

  • 对不起,这不起作用,我收到一条新错误消息“无法打开登录请求的数据库”@Mohammad
  • jes,你的连接字符串 C:\ 有空格
  • @depressedGirl 这是一个身份验证问题,请检查您的数据库身份验证。
  • 数据库身份验证是什么意思,我可以访问数据库,直到我点击按钮@Mohammad
  • 您当前正在使用 Windows 身份验证登录 SQL。使用 SQL 身份验证创建一个单独的用户,然后尝试使用此连接字符串登录。
【解决方案2】:

既然是 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

【讨论】:

  • 我只是直接复制了我数据库的连接字符串
猜你喜欢
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 2018-01-28
  • 2012-05-20
  • 2016-09-26
  • 2017-08-14
相关资源
最近更新 更多