【发布时间】:2014-02-09 19:02:46
【问题描述】:
您好,我正在尝试从文本框中显示的数据库中获取数据。为此,我创建了三个类:Dal、Controller 和 TestForm。问题是我真的不知道在哪里打开连接,也不知道在哪里关闭它。这就是我所做的。
在我的 Dal 课上:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Odbc;
namespace TestingDatabaseConnection
{
class Dal
{
private SqlConnection connection = new SqlConnection();
public SqlConnection GetConnection()
{
if (connection == null)
{
connection.ConnectionString = "Server=Mnemonics-DAT;Database=mem; Integrated Security = true;";
}
return connection;
}
public SqlDataReader GetData()
{
SqlDataReader sqlReads = null;
SqlCommand sqlCommand = new SqlCommand("select * from table_name", GetConnection());
sqlReads = sqlCommand.ExecuteReader();
return sqlReads;
}
}
}
在控制器类中我有:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestingDatabaseConnection
{
class Controller
{
private Dal dal = new Dal();
public SqlDataReader GetData()
{
return dal.GetData();
}
}
}
最后是形式:
public partial class TestForm : Form
{
Controller controll;
public TestForm()
{
InitializeComponent();
controll = new Controller();
}
private void showBtn_Click(object sender, EventArgs e)
{
try
{
SqlDataReader sqlReader = controll.GetData();
while (sqlReader.Read())
{
infTxtBox.Text = sqlReader.ToString();
}
}
catch (Exception e1)
{
MessageBox.Show("Something is wrong: " + e1);
}
}
}
我收到的消息说“出了点问题:ExecuteReader 需要一个打开且可用的连接。连接的当前状态为关闭。
我试图解决问题的方法(在 Dal 类中):
制作一个像这样获取连接值的属性:
public SqlConnection Connect
{
get
{
return connection;
}
}
然后在GetData()方法中使用它:
public SqlDataReader GetData()
{
SqlDataReader sqlReads = null;
try
{
//I call the method Open() here
Connect.Open();
SqlCommand sqlCommand = new SqlCommand("select * from table_name", GetConnection());
sqlReads = sqlCommand.ExecuteReader();
}
catch (Exception e)
{
Console.WriteLine("Error is: " + e);
}
finally
{
//and close it here
Connect.Close();
}
return sqlReads;
}
我现在收到的错误消息是:“出了点问题:阅读器关闭时调用 Read 的尝试无效” 在引用类 TestForm 时。
【问题讨论】:
标签: c# database datareader