在winform程序中要操作mysql數據庫,首先要引用“using MySql.Data.MySqlClient;”然后按照本文中的代碼即可實現最簡單的數據庫操作
private void bt_connect_Click(object sender, EventArgs e)
{
string ConnString = "server=localhost;database=test;user id=root;password=neal";
MySqlConnection conn = new MySqlConnection(ConnString);
try
{
//打開連接
conn.Open();
#region//查詢數據
//string sql = string.Format("select name from table2 where id=1");
//MySqlCommand cmd = new MySqlCommand(sql, conn);
//string result="未執行";
//MySqlDataReader reader = cmd.ExecuteReader();
//try
//{
// while (reader.Read())
// {
// if (reader.HasRows)
// {
// result = "編號:" + reader.GetInt32(0) + "|姓名:" + reader.GetInt32(0) + "|年齡:" + reader.GetInt32(0);
// }
// }
//}
//catch (Exception)
//{
// result= "查詢失敗了!";
//}
//finally
//{
// reader.Close();
//}
#endregion
#region//插入數據
//string sql_insert = "insert into table2 values (5,55,55)";
//string result = "未執行";
//MySqlCommand cmd_insert = new MySqlCommand(sql_insert, conn);
//try
//{
// cmd_insert.ExecuteNonQuery();
// result = "插入成功";
//}
//catch (Exception ex)
//{
// result = "插入失敗:" + ex.Message;
//}
#endregion
#region//修改數據
//string sql_update = "update table2 set name=111 where id= 1";
//string result = "未執行";
//MySqlCommand cmd_update = new MySqlCommand(sql_update, conn);
//try
//{
// cmd_update.ExecuteNonQuery();
// result = "修改成功";
//}
//catch (Exception ex)
//{
// result = "修改失敗" + ex.Message;
//}
#endregion
string sql_delete = "delete from table2 where id = 1";
string result = "未執行";
MySqlCommand cmd_delete = new MySqlCommand(sql_delete, conn);
try
{
cmd_delete.ExecuteNonQuery();
result = "刪除成功";
}
catch (Exception ex)
{
result = "刪除失敗" + ex.Message;
}
//如果當前狀態打開,在控制台輸出
if (conn.State == ConnectionState.Open)
{
tb_db_OpenOrClose.Text = "當前數據庫已經連接!
";
tb_db_OpenOrClose.Text += "連接字符串為:" + conn.ConnectionString+"記錄數量:"+result;
}
}
catch (Exception ex)
{
tb_db_OpenOrClose.Text = "當前數據庫已經失敗!
";
tb_db_OpenOrClose.Text += "失敗的原因是:" + ex.Message;
}
finally
{
//調用Close方法即使關閉連接
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
Neal 2014.11.29