C#基于MySQL驱动(VS2012)操作MariaDB
MariaDB最近越来越热,于是也下了个来捣腾捣腾。我下的是mariadb-10.0.4-win32.msi,但是安装完后,想用C#进行连接时,发现没有可
MariaDB最近越来越热,于是也下了个来捣腾捣腾。我下的是mariadb-10.0.4-win32.msi,但是安装完后,想用C#进行连接时,发现没有可以用的驱动。网上找了一番后,说是MaraiDB兼容MySQL,所以可以用MySQL的驱动来连接。不过,有文提到MariaDB5.5相当于MySQL的5.5,,而MariaDB10.0.4相当于MySQL5.6,而MySQL现在已经是6.7了,所以下载MySQL驱动的时候要特别注意,还有要注意的是mariadb是32还是64位的,搞错了,连接会出问题。
在下MySQL驱动的时候本来想在官网下的,但是要帐号,所以就另找了个镜像点下。这是镜像点,我下的是MySQL-connector-net-5.2.7。
下面是具体实现的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MariaDBTest
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
MySqlConnection connection_;
private void buttonOpenConnect_Click(object sender, EventArgs e)
{
string connectionStr = "server=localhost;user id=root;password=abc;database=test";
connection_ = new MySqlConnection(connectionStr);
connection_.Open();
MessageBox.Show("Connect OK!");
}
private void buttonSelect_Click(object sender, EventArgs e)
{
if (connection_ == null)
{
MessageBox.Show("Please open connect!");
return;
}
string sql = "SELECT * FROM MyTable";
MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection_);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
dataGridViewMariaDB.DataSource = dataTable;
}
private void buttonCloseConnect_Click(object sender, EventArgs e)
{
if (connection_ != null)
{
connection_.Close();
MessageBox.Show("Connect Close!");
}
}
private void buttonInsert_Click(object sender, EventArgs e)
{
if (connection_ == null)
{
MessageBox.Show("Please open connect!");
return;
}
int no = DateTime.Now.Second;
int sum = DateTime.Now.Millisecond;
string sql = string.Format("INSERT INTO MyTable (`NO`,`Sum`) VALUES({0},{1});", no, sum);
MySqlCommand command = new MySqlCommand(sql, connection_);
int affectLines = command.ExecuteNonQuery();
MessageBox.Show("Affect " + affectLines.ToString() + " line");
}
private void buttonDelete_Click(object sender, EventArgs e)
{
if (connection_ == null)
{
MessageBox.Show("Please open connect!");
return;
}
int no = Convert.ToInt32(textBoxNO.Text);
string sql = string.Format("DELETE FROM MyTable WHERE `NO`={0}", no);
MySqlCommand command = new MySqlCommand(sql, connection_);
int affectLines = command.ExecuteNonQuery();
MessageBox.Show("Affect " + affectLines.ToString() + " line");
}
}
}
这里有几点需要注意的: