1

I want to return DataReader from a Function. so i can use it regardless of its is MySQL or 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(); } } 
4
  • 2
    Did you have a look to see if they share a common base class? Hint: They do. Commented Dec 15, 2014 at 12:06
  • your best bet is to return msdn.microsoft.com/en-us/library/… Commented Dec 15, 2014 at 12:09
  • Try using ODBC (OdbcConnection, etc.) - it will unify the databases. Commented Dec 15, 2014 at 12:11
  • 2
    But why is your method void if you want to return something? Commented Dec 15, 2014 at 12:12

1 Answer 1

2

You could make the return type of your method to be IDataReader since both SqlDataReader and MySqlDataReader implement this interface.

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; } 

Furthermore, I think that you should pass as an argument to your Connection method the type of the database.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes that works but then i have the problem that IDataReader dossent have .HasRows any nice little solution to that also and then it woudt be gold ?
@Kaalund one thing that I would give it a go, If I were in your position, it would be using a while, while (dataReader.Read()). This way you could check if the dataReader has rows and in each step of the while, while the condition is true,dataReader.Read()==true, read the current value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.