我想从函数返回DataReader
。所以我可以使用它,无论它是MySQL还是MS-SQL?
private void Connection(string Command)
{
if (DBtype == "MySQL")
{
MySqlConnection MysqlConnection1 = new MySqlConnection(CS);
MySqlCommand MySqlcommand = new MySqlCommand(Command, MysqlConnection1);
MysqlConnection1.Open();
MySqlDataReader reader = MySqlcommand.ExecuteReader();
}
else
{
SqlConnection sqlConnection1 = new SqlConnection(CS);
SqlCommand Sqlcommand = new SqlCommand(Command, sqlConnection1);
sqlConnection1.Open();
SqlDataReader reader = Sqlcommand.ExecuteReader();
}
}
答案 0 :(得分:2)
您可以将方法的返回类型设为IDataReader
,因为SqlDataReader
和MySqlDataReader
都会实现此接口。
private IDataReader Connection(string Command)
{
IDataReader dataReader = null;
if (DBtype == "MySQL")
{
MySqlConnection MysqlConnection1 = new MySqlConnection(CS);
MySqlCommand MySqlcommand = new MySqlCommand(Command, MysqlConnection1);
MysqlConnection1.Open();
dataReader = MySqlcommand.ExecuteReader();
}
else
{
SqlConnection sqlConnection1 = new SqlConnection(CS);
SqlCommand Sqlcommand = new SqlCommand(Command, sqlConnection1);
sqlConnection1.Open();
dataReader = Sqlcommand.ExecuteReader();
}
return dataReader;
}
此外,我认为您应该将Connection
方法作为参数传递给数据库的类型。