先添加引用 Mysql.Data.dll 组件
在头文件中添加usingMySql.Data.MySqlClient
例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;//导入用MySql的包
using System.Data;//引用DataTable
namespace TestMysql
{
public class DBHelper
{
/// <summary>
/// 得到连接对象
/// </summary>
/// <returns></returns>
public MySqlConnection GetConn()
{
MySqlConnection mysqlconn = newMySqlConnection("Database='"+database+"';DataSource='"+local+"';UserId='"+user+"';Password='"+password+"'");
return mysqlconn;
}
}
public class SQLHelper : DBHelper
{
/// <summary>
/// 查询操作
/// </summary>
/// <paramname="sql"></param>
/// <returns></returns>
public DataTable Selectinfo(string sql)
{
MySqlConnection mysqlconn = null;
MySqlDataAdapter sda = null;
DataTable dt = null;
try
{
mysqlconn = base.GetConn();
sda = new MySqlDataAdapter(sql, mysqlconn);
dt = new DataTable();
sda.Fill(dt);
return dt;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 增删改操作
/// </summary>
/// <paramname="sql">sql语句</param>
/// <returns>执行后的条数</returns>
public int AddDelUpdate(string sql)
{
MySqlConnection conn = null;
MySqlCommand cmd = null;
try
{
conn = base.GetConn();
conn.Open();
cmd = new MySqlCommand(sql,conn);
int i = cmd.ExecuteNonQuery();
return i;
conn.Close();
}
catch (Exception)
{
throw;
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TestMysql
{
public partial class Form1 : Form
{
/// <summary>
/// SQLHlper类的对象
/// </summary>
SQLHelper helper = new SQLHelper();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string name = "";
string sql = string.Format("select*from stuinfo");
DataTable dt = helper.Selectinfo(sql);
for (int i =0; i < dt.Rows.Count; i++)
{
//从数据库得到stuname 字段的值
name+=(string)dt.Rows[i]["stuname"]+"\r\n";
}
//把得到的值放到文本框中
this.textBox1.Text = name;
}
/// <summary>
/// 退出按钮
/// </summary>
/// <paramname="sender"></param>
/// <paramname="e"></param>
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
/// <summary>
/// 增加按钮
/// </summary>
/// <paramname="sender"></param>
/// <paramname="e"></param>
private void btnAdd_Click(object sender, EventArgs e)
{
string sql = string.Format("insertinto userinfo values('{0}','{1}')",this.txtname.Text,txtpwd.Text);
int i = helper.AddDelUpdate(sql);
if (i>0)
{
MessageBox.Show("增加成功");
}
}
}
}