我遇到了一个问题,我遇到了一个异常,但我不确定如何处理它,正如我所想的那样。
在 reader = command.ExecuteReader()
上,我收到以下异常消息:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code.
没有任何数据可以通过,这很好,这就是我添加 if(reader.HasRows)
语句的原因,以防页面加载时没有数据。
我该如何处理?
下面是缩写代码:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["LocalConnection"].ConnectionString))
{
string selectSql = "SELECT tb1,tb2 FROM Stuff INNER JOIN User ON " +
"User.Stuff_FK=Stuff.ID";
using (SqlCommand command = new SqlCommand(selectSql, connection))
{
// populate already existing data
SqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
TB1.Text = reader["tb1"].ToString();
TB2.Text = reader["tb2"].ToString();
}
reader.Close();
}
else
{
connection.Close();
}
}
}
}
最佳答案
用户
是 reserved keyword ,你需要将它包装在 []
中:
string selectSql = "SELECT tb1,tb2 FROM Stuff INNER JOIN [User] ON [User].Stuff_FK=Stuff.ID";
出于这个原因,我会选择一个不同的表名。顺便说一下,Stuff
也是一个 T-SQL 函数,但如果该表存在,它应该仍然可以工作。
关于c# - 如何解决 System.Data.SqlClient.SqlException 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27377065/