【问题标题】:SQL exception was unhandled by user code on connection open连接打开时用户代码未处理 SQL 异常
【发布时间】:2017-06-17 04:29:52
【问题描述】:

我是 microsoft asp.net 的初学者,我在 System.Data.dll 中发生了“System.Data.SqlClient.SqlException”类型的异常,但在尝试从 Microsoft Visual 中选择值时未在用户代码错误中处理工作室数据库。错误出现在 con.Open() 行

下面是我的代码:

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Ng\Documents\Visual Studio 2015\Projects\Assignment6\Assignment6\App_Data\photoCompetition.mdf;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");

    protected void Button1_Click(object sender, EventArgs e)
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE email=@username and password=@word", con);
                cmd.Parameters.AddWithValue("@username", emailtext.Text);
                cmd.Parameters.AddWithValue("@word", passwordtext.Text);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                int i = cmd.ExecuteNonQuery();
                con.Close();

                if (dt.Rows.Count > 0)
                {
                    Response.Redirect("Default.aspx");
                }
                else
                {
                    lblMsg.Text = "Your username and word is incorrect";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
            }

【问题讨论】:

  • 为什么C: \Users\Ng\Documents\Visual Studio 2015\Projects\Assignment6\Assignment6\App_Data\photoCompetition.mdf中有空格?尝试先将其删除。还可以在 SqlConnection 上使用 using 关键字来正确处理它。
  • 您是否尝试将代码包装在 try...catch 块中并检查问题所在?
  • 我删除了空格,但现在错误出现在 sda.Fill(dt) 行...

标签: c# asp.net sql-server database entity-framework


【解决方案1】:

所以你的第一个问题是你的 Sql 连接字符串中有一个空格。

C: \Users\Ng\Documents\Visual Studio 2015\Projects\Assignment6\Assignment6\App_Data\photoCompetit‌​ion.mdf

现在,由于您的查询看起来有效并且假设表和列存在,您尝试执行的 SQL 查询存在问题。我在这里看到两个选项。

  1. 用单引号将参数括起来以将其表示为字符串

    SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE email='@username' and password='@word'", con);
    
  2. 使用SqlParameterCollection.Add Method (String, SqlDbType, Int32)

    cmd.Parameters.Add("@username", SqlDbType.Text).Value = emailtext.Text;
    cmd.Parameters.Add("@word", SqlDbType.Text).Value = passwordtext.Text;
    

另外,别忘了用con.Close();关闭你的SqlConnection

【讨论】:

  • 我已经修改了我的代码,但 sda.fill 行仍然出现错误消息附加信息:关键字“用户”附近的语法不正确。
  • 命令设置如下:SqlCommand cmd = new SqlCommand("SELECT * FROM [User] WHERE email=@username and password=@word", con); 不需要引号。
  • @mjwills 你显然没有明白我所说的。祝你好运。
  • 你能指出我误解了哪一部分吗?我从未见过这样的参数加上引号(因为不需要它们)。您能指出我们在其他地方看到过使用该技术的地方吗?此外,您需要 [ 和 ] 在 User 周围,因为它是 SQL Server 保留字 - 请参阅docs.microsoft.com/en-us/sql/t-sql/language-elements/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-12
  • 1970-01-01
相关资源
最近更新 更多