方法1、通过MySQLDriverCS来连接数据库
先安装:MySQLDriverCS-n-EasyQueryTools-4.0.1-DotNet2.0.exe
下面是我用MySQLDriverCS连接数据库的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MySql.Data.MySqlClient; //引入命名空间
namespace BaiheIDControl
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string ip = "localhost"; // 需要修改ip在这里
private string databasename = "addressbook"; //数据库名称
private string username = "root"; //数据库用户名
private string password = "root"; //数据库密码
private string tabalename = "users"; //数据库表
private DataTable sourtable = new DataTable();
private MySqlCommandBuilder mycb = null;
private MySqlDataAdapter myadp = null;
private MySqlConnection mycon = null;
private void Form1_Load(object sender, EventArgs e)
{
KuBiYu(ip);
}
private void FillData()
{
this.sourtable.Clear();
this.myadp.Fill(this.sourtable);
}
private void KuBiYu(string IP)
{
this.mycon = new MySqlConnection("Database="+databasename+";Data Source=" + IP + ";User Id="+username+";Password="+password);
this.mycon.Open();
this.myadp = new MySqlDataAdapter("select * from "+tabalename, this.mycon);
this.mycb = new MySqlCommandBuilder(myadp);
this.dataGridView1.DataSource = this.sourtable;
this.FillData();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Help.ShowHelp(this,"http://www.kubiyu.com");
}
private void button1_Click(object sender, EventArgs e)
{
Form2 fr2 = new Form2();
fr2.Show();
}
}
}
方法2、使用MySql.Data.MySqlClient 连接MySQL数据库
使用方式很简单,这里只需要添加一个mysql.data.dll 这个引用就可以了
下面是我的用这种方式查询的源代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySQLDriverCS; //引入命名空间
namespace BaiheIDControl
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private string ip = "localhost"; // 需要修改ip在这里
private string databasename = "addressbook"; //数据库名称
private string username = "root"; //数据库用户名
private string password = "root"; //数据库密码
private string tabalename = "users"; //数据库表
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Help.ShowHelp(this, "http://www.kubiyu.com");
}
private void Form2_Load(object sender, EventArgs e)
{
KuBiYu(ip);
}
private void KuBiYu(string IP)
{
MySQLConnection conn = null;
try
{
conn = new MySQLConnection(new MySQLConnectionString(IP, databasename, username, password).AsString);
conn.Open();
MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
commn.ExecuteNonQuery();
string sql = "select * from "+tabalename;
MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
DataSet ds = new DataSet();
mda.Fill(ds, "table1");
dataGridView1.DataSource = ds.Tables["table1"];
}
catch
{
MessageBox.Show("连接数据库失败", "友情提示");
}
finally
{
conn.Close();
}
}
}
}