I'm writing a simple console application in C# using top-level statements, and I want to check at the beginning whethere there exists a database. Here's my code:
using MySql.Data.MySqlClient;
using (MySqlConnection connection = new MySqlConnection("Server=localhost;Uid=root;Pwd=password;"))
{
connection.Open();
if (CheckDatabaseExistence(connection)) Console.WriteLine("Database Exists.");
}
bool CheckDatabaseExistence(MySqlConnection connection)
{
MySqlCommand myCommand = connection.CreateCommand();
myCommand.CommandText = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA" +
"WHERE SCHEMA_NAME LIKE 'database_name';";
return Convert.ToInt32(myCommand.ExecuteScalar()) == 1;
}
After executing this code, I get the following error message:
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIKE 'sql_store'' at line 1'
The SQL query syntax for checking database existence is from MySQL Documentation, Section 24.3.22
SELECT SCHEMA_NAME AS `Database`
FROM INFORMATION_SCHEMA.SCHEMATA
[WHERE SCHEMA_NAME LIKE 'wild']
I've tried replacing LIKE
with =
, but I get the same error.
To check if a database exists in MySQL using a
Console App
, try the following:Create a
Console App
VS 2022:
Open Solution Explorer:
Open Properties Window
Install/Download NuGet package:
MySql.Data
Option 1 (Application Configuration File)
Add an
Application Configuration File
to your project (name: App.config)App.config:
Add a class (name: HelperMySql.cs)
HelperMySql.cs:
Option 2
Add a
JavaScript JSON Configuration File
to your project (name: appsettings.json)appsettings.json:
Set File Properties:
Install/Download NuGet package:
Microsoft.Extensions.Configuration.Json
Add a class (name: HelperMySql.cs)
HelperMySql.cs:
Program.cs
Resources: