由于需要实现以下功能:
网关通过串口发送数据给PC机,PC机收集数据并解析保存到MySQL中,然后JSP页面读取MySQL中的数据并显示。
所以利用C#连接MySQL数据成为了必须要经过的过程,在此给予详细的说明。
1、下载需要的文件MySQLDriverCS,下载地址为:http://sourceforge.net/projects/mysqldrivercs
2、安装文件:MySQLDriverCS-n-EasyQueryTools-4.0.1-DotNet2.0.exe,在安装过程中也许会提示一个错误,禁止写一个dll文件,你直接忽略就可以了。
3、将安装文件下的MySQLDriver.dll文件添加到C#项目的引用中。
4、然后写公共处理类如下:
(1) 首先得引用命名空间:
using MySQLDriverCS;
using System.Data;
using System.Data.Odbc;
(2) 写公共处理类
public class SQLHelper
{
MySQLConnection conn = null;
MySQLCommand commn = null;
public MySQLConnection GetConnect()
{
conn = new MySQLConnection(new MySQLConnectionString("localhost", "wwater", "root", "123").AsString);
return conn;
}
public int RunMySQL(string sql)
{
int count = 0;
try
{
conn = GetConnect();
conn.Open();
commn = new MySQLCommand(sql, conn);
count = commn.ExecuteNonQuery();
return count;
}
catch (Exception ex)
{
throw;
}
finally
{
conn.Close();
}
}
}
(3) 在实际过程中进行引用RunMySQL方法即可插入数据了。