在winform程序中要操作mysql数据库,首先要引用“using MySql.Data.MySqlClient;”然后按照本文中的代码即可实现最简单的数据库操作
<span style="font-size:18px;">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 = "当前数据库已经连接!<br/>";
tb_db_OpenOrClose.Text += "连接字符串为:" + conn.ConnectionString+"记录数量:"+result;
}
}
catch (Exception ex)
{
tb_db_OpenOrClose.Text = "当前数据库已经失败!<br/>";
tb_db_OpenOrClose.Text += "失败的原因是:" + ex.Message;
}
finally
{
//调用Close方法即使关闭连接
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}</span>
Neal 2014.11.29