1 C#与mysql连接
需要下载插件:mysql.data.dll,下载地址http://hovertree.com/h/bjaf/0sft36s9.htm,下载后右键项目-》引入–浏览–选择要引入的文件。
mysql.data.dll是C#操作MYSQL的驱动文件,是c#连接mysql必要插件,使c#语言更简洁的操作mysql
数据库。当你的电脑弹出提示“丢失mysql.data.dll”或“无法找到mysql.data.dll”等错误问题,请下载本站为你提供的dll文件,使用它可以帮助用户解决上述问题。
dll文件修复方法:
1、解压下载的文件。
2、复制文件“mysql.data.dll”到系统目录下。
3、系统目录一般为:C:\WINNT\System32 64位系统为C:\Windows\SysWOW64
4、最后点击开始菜单–>运行–>输入regsvr32 mysql.data.dll 后,回车即可解决错误提示!
连接数据库的代码:
//mysql连接
MySqlConnection mycon;
string constr = "server=localhost;User Id=root;password=123123;Database=graduation_project";
mycon = new MySqlConnection(constr);
2 C#实现简单的操作MySql数据库:增删改查
增:
StringBuilder sqlStr = new StringBuilder();
sqlStr.Append("insert into temperature(temperature,serial_port,baud_rate,stop_bit,data_bit,parity_check_bit,flag,create_time)");
sqlStr.Append("values('" + a/10 + "','" + comboBox1.Text + "','" + comboBox2.Text+"','" + comboBox3.Text + "'," + comboBox4.Text + ",'" + comboBox5.Text + "'," + "'M'" + ",'" + DateTime.Now + "')");
Console.WriteLine(sqlStr);
openConnection();
try
{
MySqlCommand mycmd = new MySqlCommand(sqlStr.ToString(), mycon);
if (mycmd.ExecuteNonQuery() > 0)
{
Console.WriteLine("数据插入成功!");
}
Console.ReadLine();
}
catch (Exception)
{
closeConnection();
MessageBox.Show("插入数据出错!");
return;
}
删与改:
StringBuilder sqlStr = new StringBuilder();
sqlStr.Append("update temperature set flag='D',delete_time='" + DateTime.Now + "' where flag='M'");
Console.WriteLine(sqlStr);
openConnection();
try
{
MySqlCommand mycmd = new MySqlCommand(sqlStr.ToString(), mycon);
if (mycmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("清空成功");
}
Console.ReadLine();
}
catch (Exception)
{
closeConnection();
MessageBox.Show("清空出错!请再次操作");
}
closeConnection();
查:
string strSQL2 = "select * from alarm_temp where flag='M'";
openConnection();
MySqlCommand mycomTemp = mycon.CreateCommand();
mycomTemp.CommandText = strSQL2;
MySqlDataAdapter adapTemp = new MySqlDataAdapter(mycomTemp);
closeConnection();
根据状态打开数据库:
//打开数据库;连接
public void openConnection(){
if (mycon.State != ConnectionState.Open)
{
mycon.Open();
}
}
根据状态关闭数据库:
//关闭数据库连接
public void closeConnection() {
if (mycon.State != ConnectionState.Closed)
{
mycon.Close();
}
}
附报错及解决方案:
1 VS报错:线程间操作无效: 从不是创建控件“comboBox1”的线程访问它。
原因:在多线程程序中,新创建的线程不能访问UI线程创建的窗口控件,
解决方案:
legalCrossThreadCalls设置为 false
解决方案:
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
参考博客:http://www.cnblogs.com/hongfei/archive/2012/12/08/2808771.html
2 报错:There is already an open DataReader associated with this
Connection which must be closed first.
解决方案:
DataReader和Connection在使用连接后记得关闭,
未完待续。。。