简体   繁体   中英

C# Connect to a MySQL database

I'm trying to connect to a MySQL database without any success. I found a lot of examples but neither of them worked for me.

I installed the NuGet Connector.Net package and used the following code:

  string DBcon = "Server=localhost;Database=world.sql;Uid=root;Pwd=password;";

    using (MySqlConnection db = new MySqlConnection(DBcon))
    {
        db.Open();
        MessageBox.Show("Success");          
    }

I even installed MySQL Server but it still doesn't work. I get the following error: Authentication to host 'localhost' for user 'root' using method 'mysql_native_password' failed with message: Unknown database 'world.sql'

world.sql is a file name not a database.

you need to change

string DBcon = "Server=localhost;Database=world.sql;Uid=root;Pwd=password;";

to

string DBcon = "Server=localhost;Database=databaseName;Uid=root;Pwd=password;";

edit 1

this should help you run the SQL

conn.Open();
s0 = File.ReadAllText("path to file") 
cmd = new MySqlCommand(s0, conn);
cmd.ExecuteNonQuery();
conn.Close();

which is an adaptation of the answer from this link create database in mySQL from .Net

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