0

Beginner here. On the MySQL prompt, you can type USE database_name to select the database you are working with ; and help to make the queries easier.

I wonder if the same can be done in c#?

What I'm trying to do is to make a connection with a database, make a connection string without the file, then select it with USE database_name and the returned value will be used to check if the db exist or not. I've seen other solutions, but none using this. So iIm curious if it's possible and which MysqlCommand method should I use.

6
  • 3
    Why would you need to issue the "USE database_name" when the connection string should already state the database name? See the connection string examples at connectionstrings.com/mysql-connector-net-mysqlconnection and use exception handling to trap whenever there is a connection error. Commented Jul 25, 2018 at 8:45
  • Why not rather ask the database server if the database exists? And to my knowledge this isn’t possible. You could write a connection string and try connecting and see what error you get but as mentioned, you can ask the server if it exists or not. Commented Jul 25, 2018 at 8:45
  • @Vlam there is the problem.I tryed this way, and i get the same MysqlException.number value if the db doesnt exist or if the user and password are incorrect (returned 0 in both cases) Commented Jul 25, 2018 at 8:51
  • @SamiKuhmonen on the Mysql prompt it return an error if the db doesn't exist. I wanted to use that as a way to check it. And i said before how i get the same value for different cases when i try to make a connexion. Commented Jul 25, 2018 at 8:56
  • Then ask the server if it exists as I suggested. dev.mysql.com/doc/refman/8.0/en/schemata-table.html Commented Jul 25, 2018 at 8:59

1 Answer 1

1

You can check if a database exists by using the INFORMATION_SCHEMA.SCHEMATA table, e.g., see https://stackoverflow.com/a/838993

However, it is also possible to do what you're asking with the MySqlConnection.ChangeDatabase method (which is the same as USE database_name).

If the database exists (and your user has access to it), it will succeed. If the database doesn't exist, it will throw a MySqlException with the message "Unknown database"; exception.Number will be 1049 (i.e., MySqlErrorCode.UnknownDatabase).

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

1 Comment

This is more what i was asking. You do 2 actions with one method. Select a database and at the same time make a test with a try and catch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.