代码如下 :
using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
namespace _14._9connection链接数据库
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("请输入一个学号:");
//string stu_no = Console.ReadLine();
//Console.WriteLine();
//Console.ReadKey();
string constructorString = "server=localhost;User Id=root;password=123456;Database=test;CharSet=utf8";
MySqlConnection conn = new MySqlConnection(constructorString);
conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句
MySqlTransaction transaction = conn.BeginTransaction();//事务必须在try外面赋值不然catch里的transaction会报错:未赋值
Console.WriteLine("已经建立连接");
try
{
//在这里使用代码对数据库进行增删查改
// string sql = "select * from student ";
添加
string sql = "insert into student(name,sex,str_no) values('啊宽2',1,'s10002')";
MySqlCommand cmd = new MySqlCommand(sql, conn);
int result = cmd.ExecuteNonQuery();//3.执行插入,执行成功返回受影响的数据的行数,返回1可做true判断。执行失败不返回任何数据,报错,下面代码都不执行
if (result > 0)
{
Console.WriteLine("数据插入成功!");
}
//查询条件固定
//string sql2 = "select * from student";
//MySqlCommand cmd2 = new MySqlCommand(sql2, conn);
//MySqlDataReader reader = cmd2.ExecuteReader();
//while (reader.Read())
//{
// Console.WriteLine(reader.GetString("name") + reader.GetString("str_no") + reader.GetInt32("sex"));//"userid"是数据库对应的列名,推荐这种方式
//}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
transaction.Rollback();//事务ExecuteNonQuery()执行失败报错,username被设置unique
conn.Close();
}
finally
{
//数据
if (conn.State != ConnectionState.Closed)//ConnectionState.Closed=Closed 判断conn.state是否是关闭状态
{
transaction.Commit();//事务要么回滚要么提交,即Rollback()与Commit()只能执行一个
conn.Close();
}
}
Console.ReadKey();
}
}
}
注意这里 if (conn.State != ConnectionState.Closed)//ConnectionState.Closed=Closed 判断conn.state是否是关闭状态
{
transaction.Commit();//事务要么回滚要么提交,即Rollback()与Commit()只能执行一个
conn.Close();
}
如果try代码快没问题 conn.State=open 事务将把try里的操作提交到数据库执行生成结果 ,如果出现bug,conn.State=closs, 事务进入catch里的回滚