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.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Amine Fellous
  • 83
  • 1
  • 8
  • 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 https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/ and use exception handling to trap whenever there is a connection error. – Vlam Jul 25 '18 at 08: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. – Sami Kuhmonen Jul 25 '18 at 08: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) – Amine Fellous Jul 25 '18 at 08: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. – Amine Fellous Jul 25 '18 at 08:56
  • Then ask the server if it exists as I suggested. https://dev.mysql.com/doc/refman/8.0/en/schemata-table.html – Sami Kuhmonen Jul 25 '18 at 08:59
  • Have you tried connecting to the "mysql" database and then issue the "SHOW DATABASES LIKE 'yourdatabasename'" command. That should return a row if the database exists. – Vlam Jul 25 '18 at 09:00

1 Answers1

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).

Bradley Grainger
  • 27,458
  • 4
  • 91
  • 108
  • 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. – Amine Fellous Jul 25 '18 at 19:11