1、要连接MySql数据库必须首先下载MySql官方的连接.net的文件,文件下载地址为http://dev.mysql.com/downloads/connector/net/6.6.html#downloads ,下载平台选择.Net&Mono,下载ZIP免安装版。
2、解压缩刚才下载的mysql-connector-net-6.6.6-noinstall.zip文件,里面有几个版本选择,在这里我选V4,
然后添加mysqlData.dll到C#项目的引用中,然后就可以编写程序进行数据库的操作了。
3、数据库操作代码 InsertMySql.cs
<pre name="code" class="csharp">using System;
using System.Collections;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;
namespace Sql
{
class InsertSql
{
public MySqlConnection myCon;
public InsertSql() //连接数据库
{
string constr = "server=localhost;User Id=root;password=016457t;Database=car_flow";
myCon = new MySqlConnection(constr);
}
public bool OpenMysql() //打开数据库
{
try
{
myCon.Open();
}
catch
{
return false;
}
return true;
}
public MySqlCommand ExcuteOrder(string sql,MySqlConnection myCon) //执行命令语句sql
{
MySqlCommand myCom = new MySqlCommand(sql, myCon);
return myCom;
}
public void GetSerchResult(MySqlCommand myCom) //获取查询结果
{
try
{
MySqlDataReader msDr = myCom.ExecuteReader();
int column = msDr.FieldCount; //获取集合列数
while (msDr.Read())
{
if (msDr.HasRows)
{
for (int i = 0; i < column; i++)
{
Console.Write(msDr.GetString(i) + " ");
}
Console.WriteLine();
}
}
msDr.Close(); //关闭数据集
}
catch(Exception e)
{
Console.WriteLine(e.Data);
Console.WriteLine("获取查询结果集出错");
}
}
public void GetDelInsertUpdateResult(MySqlCommand myCom) //获取删、插、更新执行结果
{
try
{
myCom.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Data);
Console.WriteLine("执行出错");
}
}
public void CloseMySqlConnection() //关闭数据库连接句柄
{
myCon.Close();
}
public static void Main()
{
InsertSql insertsql = new InsertSql();
string quest = "select *from car_whether where 时间=20160328"; //查询语句
insertsql.OpenMysql(); //打开数据库
MySqlCommand myCom=insertsql.ExcuteOrder(quest, insertsql.myCon); //执行操作
insertsql.GetSerchResult(myCom); //获取查询集并输出
insertsql.CloseMySqlConnection(); //关闭连接
}
}
}