我是微软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;
}
}
答案 0 :(得分:-1)
所以你的第一个问题是你的Sql连接字符串中有空格。
DateTimeFormatter
现在,由于您的查询看起来有效并且假设表和列存在,因此您正在尝试执行的SQL查询出现问题。我在这里看到两个选择。
用单引号括起您的参数,将其表示为字符串
C: \Users\Ng\Documents\Visual Studio 2015\Projects\Assignment6\Assignment6\App_Data\photoCompetition.mdf
使用SqlParameterCollection.Add Method (String, SqlDbType, Int32)。
SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE email='@username' and password='@word'", con);
另外,请勿忘记cmd.Parameters.Add("@username", SqlDbType.Text).Value = emailtext.Text;
cmd.Parameters.Add("@word", SqlDbType.Text).Value = passwordtext.Text;
与SqlConnection