要想在.Net 环境下使用 MySQL,必须引用 MySQL 的 Connector, 在 VS 中“ 项目”->“ 添加引用”->“ 浏览”,选择“MySql.Data.dll”,然后在文件开头
using MySql.Data.MySqlClient;
这个 MySql.Data.dll 可以从 MySQL 的官方网站上得到,但是下载到的要不是一个源码的 zip 包,要不就是一个 10 几 M 的 msi 安装文件,里面包含了很多其他的东西,包括 Sample 等等,实际上这几个 dll 只有几百 K 而已。所以,我打包把它单独拿出来。v2.0.rar v4.0.rar
using System; using System.Collections.Generic; using System.Text; using MySql.Data.MySqlClient; namespace MySQL { class Program { static void Main(string[] args) { try { MySqlConnection conn = new MySqlConnection("server=Server;uid=User;pwd=Pass;database=Database"); MySqlCommand cmd = new MySqlCommand("show databases;", conn); conn.Open(); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader.GetValue(0).ToString()); } conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } } }