我是ASP.Net&的新手。 SQL Server并具有以下代码:
protected void btnShowData_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = @"Data Source=DESKTOP-RV7DDL4;Initial Catalog=Demodb
;User ID=DESKTOP-RV7DDL4\dbname;Password=test123";
cnn = new SqlConnection(connectionString);
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = "";
sql = "Select TutorialID, TutorialName from demotb";
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
lblName.Visible = false;
txtName.Visible = false;
lstLocation.Visible = false;
chkC.Visible = false;
chkASP.Visible = false;
rdMale.Visible = false;
rdFemale.Visible = false;
btnSubmit.Visible = false;
}
当我运行项目时,我收到以下错误:
System.Data.dll中出现'System.InvalidOperationException'类型的异常,但未在用户代码中处理
其他信息:ExecuteReader需要一个开放且可用的连接。连接的当前状态已关闭。
我认为连接是这样的,所以不确定为什么它说数据库已关闭?
答案 0 :(得分:0)
尝试通过SQL连接类上的Open method显式打开连接。
也许使用声明更合适。像这样:
using (var cnn = new SqlConnection(connectionString))
{
// Use the connection
}
答案 1 :(得分:0)
感谢您的帮助。我重新浏览了一些东西并添加了.Open方法,它可以工作!
string connectionString = null;
SqlConnection cnn;
SqlCommand command;
string sql, Output = "";
connectionString = @"Data Source=DESKTOP-RV7DDL4\SQLEXPRESS;Initial Catalog=DemoDBase
;User ID=sa;Password=test1234";
cnn = new SqlConnection(connectionString);
sql = "Select TutorialID, TutorialName from demoTable";
cnn.Open();
command = new SqlCommand(sql, cnn);
SqlDataReader dataReader;
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();