C#连接mysql实例

1、实例1

using System;
using System.Configuration;
using MySql.Data.MySqlClient;
/// 
/// TestDatebase 的摘要说明
/// 
public class TestDatebase
{
    public TestDatebase()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    public static void Main(String[] args)
    {
        MySqlConnection mysql = getMySqlCon();
        //查询sql
        String sqlSearch = "select * from student";
        //插入sql
        String sqlInsert = "insert into student values (12,'张三',25,'大专')";
        //修改sql
        String sqlUpdate = "update student set name='李四' where id= 3";
        //删除sql
        String sqlDel = "delete from student where id = 12";
        //打印SQL语句
        Console.WriteLine(sqlDel);
        //四种语句对象
        //MySqlCommand mySqlCommand = getSqlCommand(sqlSearch, mysql);
        //MySqlCommand mySqlCommand = getSqlCommand(sqlInsert, mysql);
        //MySqlCommand mySqlCommand = getSqlCommand(sqlUpdate, mysql);
        MySqlCommand mySqlCommand = getSqlCommand(sqlDel, mysql);
        mysql.Open();
        //getResultset(mySqlCommand);
        //getInsert(mySqlCommand);
        //getUpdate(mySqlCommand);
        getDel(mySqlCommand);
        //记得关闭
        mysql.Close();
       String readLine = Console.ReadLine();
    }
    /// 
    /// 建立mysql数据库链接
    /// 
    /// 
    public static MySqlConnection getMySqlCon()
    {
        String mysqlStr = "Database=test;Data Source=127.0.0.1;User Id=root;Password=root;pooling=false;CharSet=utf8;port=3306";
        // String mySqlCon = ConfigurationManager.ConnectionStrings["MySqlCon"].ConnectionString;
        MySqlConnection mysql = new MySqlConnection(mysqlStr);
        return mysql;
    }
    /// 
    /// 建立执行命令语句对象
    /// 
    /// 
    /// 
    /// 
    public static MySqlCommand getSqlCommand(String sql,MySqlConnection mysql)
    {
        MySqlCommand mySqlCommand = new MySqlCommand(sql, mysql);
        //  MySqlCommand mySqlCommand = new MySqlCommand(sql);
        // mySqlCommand.Connection = mysql;
        return mySqlCommand;
    }
    /// 
    /// 查询并获得结果集并遍历
    /// 
    /// 
    public static void getResultset(MySqlCommand mySqlCommand)
    {
        MySqlDataReader reader = mySqlCommand.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                if (reader.HasRows)
                {
                    Console.WriteLine("编号:" + reader.GetInt32(0) + "|姓名:" + reader.GetString(1) + "|年龄:" + reader.GetInt32(2) + "|学历:" + reader.GetString(3));
                }
            }
        }
        catch (Exception)
        {

            Console.WriteLine("查询失败了!");
        }
        finally
        {
            reader.Close();
        }
    }
    /// 
    /// 添加数据
    /// 
    /// 
    public static void getInsert(MySqlCommand mySqlCommand)
    {
        try
        {
            mySqlCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            String message = ex.Message;
            Console.WriteLine("插入数据失败了!" + message);
        }
     
    }
    /// 
    /// 修改数据
    /// 
    /// 
    public static void getUpdate(MySqlCommand mySqlCommand)
    {
        try
        {
            mySqlCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {

            String message = ex.Message;
            Console.WriteLine("修改数据失败了!" + message);
        }
    }
    /// 
    /// 删除数据
    /// 
    /// 
    public static void getDel(MySqlCommand mySqlCommand)
    {
        try
        {
            mySqlCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            String message = ex.Message;
            Console.WriteLine("删除数据失败了!" + message);
        }
    }
}

 

2、实例2

先添加引用Mysql.Data.dll 组件

在头文件中添加using MySql.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
    {
        /// 
        /// 得到连接对象
        /// 
        /// 
        public MySqlConnection GetConn()
        {
            MySqlConnection mysqlconn = new MySqlConnection("Database='"+database+"';Data Source='"+local+"';User Id='"+user+"';Password='"+password+"'");
            return mysqlconn;
        }
    }
 
 
    public class SQLHelper : DBHelper
    {
        /// 
        /// 查询操作
        /// 
        /// 
        /// 
        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;
            }
 
        }
 
        /// 
        /// 增删改操作
        /// 
        /// sql语句
        /// 执行后的条数
        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
    {
        /// 
        /// SQLHlper类的对象
        /// 
        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;
 
 
 
           
        }
 
        /// 
        /// 退出按钮
        /// 
        /// 
        /// 
        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
 
        }
 
        /// 
        /// 增加按钮
        /// 
        /// 
        /// 
        private void btnAdd_Click(object sender, EventArgs e)
        {
            string sql = string.Format("insert into userinfo values('{0}','{1}')",this.txtname.Text,txtpwd.Text);
            int i = helper.AddDelUpdate(sql);
            if (i>0)
            {
                MessageBox.Show("增加成功");
               
            }
        }
    }
}
 

3.实例3

不要用OLEDB,已过时。使用第三方组件:Mysql.Data.dll,在代码页里输入using Mysql.Data.MysqlClient

#region 建立MySql数据库连接
/// 
/// 建立数据库连接.
/// 
/// 返回MySqlConnection对象
public MySqlConnection getmysqlcon()
{
string M_str_sqlcon = "server=localhost;user id=root;password=root;database=abc"; //根据自己的设置
MySqlConnection myCon = new MySqlConnection(M_str_sqlcon);
return myCon;
}
#endregion

#region 执行MySqlCommand命令
/// 
/// 执行MySqlCommand
/// 
/// SQL语句
public void getmysqlcom(string M_str_sqlstr)
{
MySqlConnection mysqlcon = this.getmysqlcon();
mysqlcon.Open();
MySqlCommand mysqlcom = new MySqlCommand(M_str_sqlstr, mysqlcon);
mysqlcom.ExecuteNonQuery();
mysqlcom.Dispose();
mysqlcon.Close();
mysqlcon.Dispose();
}
#endregion

#region 创建MySqlDataReader对象
/// 
/// 创建一个MySqlDataReader对象
/// 
/// SQL语句
/// 返回MySqlDataReader对象
public MySqlDataReader getmysqlread(string M_str_sqlstr)
{
MySqlConnection mysqlcon = this.getmysqlcon();
MySqlCommand mysqlcom = new MySqlCommand(M_str_sqlstr, mysqlcon);
mysqlcon.Open();
MySqlDataReader mysqlread = mysqlcom.ExecuteReader(CommandBehavior.CloseConnection);
return mysqlread;
}
#endregion

 

 

你可能感兴趣的:(数据库,C#)