C#连接MySQL
MySQLDriverCS连接MySQL数据库
先下载和安装MySQLDriverCS,在安装文件夹下面找到MySQLDriver.dll,然后将MySQLDriver.dll添加引用到项目中
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.ComponentModel; using System.Data; using System.Data.Odbc; using MySQLDriverCS;//使用MySQLDriverCS.dll namespace MySQL { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { MySQLConnection conn = null; conn = new MySQLConnection(new MySQLConnectionString("localhost", "sakila", "root", "123456").AsString); conn.Open(); //MySQLCommand commn = new MySQLCommand("set names gb2312", conn); //commn.ExecuteNonQuery(); string sql = "select * from patient "; MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn); DataSet ds = new DataSet(); mda.Fill(ds,"patient"); dataGrid1.ItemsSource = ds.Tables["patient"].DefaultView;//找了半天终于找到DataSet转DataGrid的方法 conn.Close(); } } }
mad.Fill把表命名patient并存入DataSet