先引入
using MySql.Data.MySqlClient;
在App.config中配置
<connectionStrings>
<add name ="connStr" connectionString="server=localhost;port=3306;user=root;password=123456; database=testdb" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
使用
string connetStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; MySqlConnection conn = new MySqlConnection(connetStr); try { conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句 Console.WriteLine("已经建立连接"); //在这里使用代码对数据库进行增删查改 } catch (MySqlException ex) { Console.WriteLine(ex.Message); switch (ex.Number) { case 0: Console.WriteLine("Cannot connect to server. Contact administrator"); break; case 1045: Console.WriteLine("Invalid username/password, please try again"); break; } } finally { Console.WriteLine("关闭数据库"); conn.Close(); }