简体   繁体   中英

How to differ MySQL and MS SQL database from code?

We have two database and single method. In our case queries for MySQL and Ms SQL db are different. We need to define when use query to needed db. How can I code in C# to find which db is using now?

您可以使用天真的方法来检查将提供 sql server 等的版本,这可以在 sql server 和 mysql 中使用

SELECT @@version

If it needs to be in one method you could place using statements within one method, eg,

using(SqlConnection conn1 = new SqlConnection("FirstConnectionString"))
{
    // your Query
}


using(SqlConnection conn2 = new SqlConnection("SecondConnectionString"))
{
    // your Query
}

Where in First and Second Connections strings you define which database you refer to.

I think you can use something like this: make a new class for both methods you are using, in the mysql you put something like this, or whatever you have in your code

public void GetHighscore(int CurrScore) { MySqlConnection conn = new MySqlConnection("Server=localhost;Database=basket;Uid=root;pwd=;"); conn.Open(); MySqlCommand command = conn.CreateCommand(); command.CommandText = "select * from tblhighscore where id = 0"; command.Parameters.AddWithValue("@CurrScore", CurrScore); MySqlDataReader reader = command.ExecuteReader(); conn.Close(); }

and for the ms sql you make another class with your own queries and stuff, i think the only difference should be the name of the sql, for example: MySql would be just sql.
You can call upon the mysql one with the following code, the dbConnect.GetHighscore is a reference to a piece of code in the mysql class, it will execute all the code in that piece of code.:

dbConnect clDb = new dbConnect(); dbConnect.GetHighscore;

I would do the following:

  • Add an enum to the method input parameters which decide which kind of database should be used (You have to know this information before calling the method)
  • Inside the method, depending on the enum, I would choose the proper query and then call a different method for running the MySQL query and one for running MS SQL. In one case using OracleConnection and in the other using SqlConnection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM