一直使用的是MS SQL,和其他公司做接口時(shí)需向MySQL數(shù)據(jù)庫中寫入數(shù)據(jù),因此今天重溫C#連接MySQL.
1.首先下載Connector/Net下載完成后安裝并在項(xiàng)目中添加引用。

Paste_Image.png
2.操作MySQL數(shù)據(jù)庫和MS SQL類似,只是換了類庫。需要注意是的數(shù)據(jù)中包含DateTime數(shù)據(jù)類型且字段中值包含“000-00-00”時(shí)會(huì)拋異常,這是只需要在連接字符串中加上allow zero datetime=true"即可。

Paste_Image.png

Paste_Image.png
DataTable dt = new DataTable();
string connectionString = "server=10.0.0.234;user id=PanPan; pwd=123456;database=wordpress;allowuservariables=True;Allow Zero Datetime=True";
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from wp_posts";
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
sda.Fill(dt);
}
}
參考資料:CSDN