c#mysql操作

利用数据库提供的动态链接库MySql.Data.dll进行操作。MySql.Data.dll提供以下8个类:

  • MySqlConnection: 连接MySQL服务器数据库。
  • MySqlCommand:执行一条sql语句。
  • MySqlDataReader: 包含sql语句执行的结果,并提供一个方法从结果中阅读一行。
  • MySqlTransaction: 代表一个SQL事务在一个MySQL数据库。
  • MySqlException: MySQL报错时返回的Exception。
  • MySqlCommandBuilder: Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated MySQL database.
  • MySqlDataAdapter: Represents a set of data commands and a database connection that are used to fill a data set and update a MySQL database.
  • MySqlHelper: Helper class that makes it easier to work with the provider.

    建立连接(MySqlConnection类)

    using MySql.Data.MySqlClient;
    
    String connetStr = "server=127.0.0.1;port=3306;user=root;password=root; database=minecraftdb;";
    // server=127.0.0.1/localhost 代表本机,端口号port默认是3306可以不写
    MySqlConnection conn = new MySqlConnection(connetStr);
    try
    {    
          conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句
          Console.WriteLine("已经建立连接");
          //在这里使用代码对数据库进行增删查改
    }
    catch (MySqlException ex)
    {
          Console.WriteLine(ex.Message);
    }
    finally
    {
          conn.Close();
    }

     

     

    增删查改的代码(MySqlCommand类、MySqlDataReader类)

      ExecuteReader——用于查询数据库。查询结果是返回MySqlDataReader对象,MySqlDataReader包含sql语句执行的结果,并提供一个方法从结果中阅读一行。

      ExecuteNonQuery——用于插入、更新和删除数据。

      ExecuteScalar——用于查询数据时,返回查询结果集中第一行第一列的值,即只返回一个值。

      (1)   查询

      a.查询条件固定

    string sql= "select * from user";
    MySqlCommand cmd = new MySqlCommand(sql,conn);
    MySqlDataReader reader =cmd.ExecuteReader();//执行ExecuteReader()返回一个MySqlDataReader对象
    while (reader.Read())//初始索引是-1,执行读取下一行数据,返回值是bool
    {
        //Console.WriteLine(reader[0].ToString() + reader[1].ToString() + reader[2].ToString());
        //Console.WriteLine(reader.GetInt32(0)+reader.GetString(1)+reader.GetString(2));
        Console.WriteLine(reader.GetInt32("userid") + reader.GetString("username") + reader.GetString("password"));//"userid"是数据库对应的列名,推荐这种方式
    }

     

      b.查询条件不固定

  • //string sql = "select * from user where username='"+username+"' and password='"+password+"'"; //我们自己按照查询条件去组拼
    string sql = "select * from user where username=@para1 and password=@para2";//在sql语句中定义parameter,然后再给parameter赋值
    MySqlCommand cmd = new MySqlCommand(sql, conn);
    cmd.Parameters.AddWithValue("para1", username);
    cmd.Parameters.AddWithValue("para2", password);
    
    MySqlDataReader reader = cmd.ExecuteReader();
    if (reader.Read())//如果用户名和密码正确则能查询到一条语句,即读取下一行返回true
    {
        return true;
    }

      c.需要查询返回一个值

  • string sql = "select count(*) from user";
    MySqlCommand cmd = new MySqlCommand(sql, conn);
    Object result=cmd.ExecuteScalar();//执行查询,并返回查询结果集中第一行的第一列。所有其他的列和行将被忽略。select语句无记录返回时,ExecuteScalar()返回NULL值
    if (result != null)
    {
        int count = int.Parse(result.ToString());
    }

     

      (2)   插入、删除、更改

    string sql = "insert into user(username,password,registerdate) values('啊宽','123','"+DateTime.Now+"')";
    //string sql = "delete from user where userid='9'";
    //string sql = "update user set username='啊哈',password='123' where userid='8'";
    MySqlCommand cmd = new MySqlCommand(sql,conn);
    int result =cmd.ExecuteNonQuery();//3.执行插入、删除、更改语句。执行成功返回受影响的数据的行数,返回1可做true判断。执行失败不返回任何数据,报错,下面代码都不执行

     

     事务(MySqlTransaction类)

     

    String connetStr = "server=127.0.0.1;user=root;password=root;database=minecraftdb;";
    MySqlConnection conn = new MySqlConnection(connetStr);
    conn.Open();//必须打开通道之后才能开始事务
    MySqlTransaction transaction = conn.BeginTransaction();//事务必须在try外面赋值不然catch里的transaction会报错:未赋值
    Console.WriteLine("已经建立连接");
    try
    {
        string date = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;
        string sql1= "insert into user(username,password,registerdate) values('啊宽','123','" + date + "')";
        MySqlCommand cmd1 = new MySqlCommand(sql1,conn);
        cmd1.ExecuteNonQuery();
    
        string sql2 = "insert into user(username,password,registerdate) values('啊宽','123','" + date + "')";
        MySqlCommand cmd2 = new MySqlCommand(sql2, conn);
        cmd2.ExecuteNonQuery();
    }
    catch (MySqlException ex)
    {
        Console.WriteLine(ex.Message);
        transaction.Rollback();//事务ExecuteNonQuery()执行失败报错,username被设置unique
        conn.Close();
    }
    finally
    {
        if (conn.State != ConnectionState.Closed)
        {
            transaction.Commit();//事务要么回滚要么提交,即Rollback()与Commit()只能执行一个
            conn.Close();
        }
    }

    转载https://www.cnblogs.com/DonYao/p/8438375.html

 

备注:

  string str = "Host=localhost;User ID=root;Password=;Port = 3306;DataBase=animals;Charset=utf8;";
            MySqlConnection conn = new MySqlConnection(str);
            conn.Open();//
                        ////拿到数据库并打开连接
                        //string sql = "select *from student";
                        //MySqlCommand cmd = new MySqlCommand(sql, conn);
                        //MySqlDataAdapter mda = new MySqlDataAdapter(cmd);
                        //DataSet ds = new DataSet();
                        //mda.Fill(ds);
                        //dataGridView1.DataSource = ds.Tables[0];
                        ////MySqlDataReader dr = cmd.ExecuteReader();
                        //conn.Close();
            /*1.访问数据库的五大步骤
              2.拿到要发送的sql语句
              3.执行 sql 语句
              4.拿到执行后的聚过
              5.关闭连接 切记关闭连接
            */
            ////1 拿到数据库的连接 并打开连接
            //string url = "User ID=root;Password=;Host=localhost;Port=3306;Database=xx;charset=xx;";
            //MySqlConnection con = new MySqlConnection(url);
            //con.Open();
            ////2.要拿到要发送的sql语句
            //string sql = "select id from student where name='kobe'";
            //MySqlCommand com = new MySqlCommand(sql, con);
            //// 3 执行 sql 语句
            //MySqlDataReader reader = com.ExecuteReader();
            //reader.Read();// Read() 每次调用 都会从结果集中返回一行数据
            //reader.GetInt32(0);
            /*1.访问数据库的五大步骤
              2.拿到要发送的sql语句
              3.执行 sql 语句
              4.拿到执行后的聚过
              5.关闭连接 切记关闭连接
            */
            //1 拿到数据库的连接 并打开连接
            string url = "User ID=root;Password=;Host=localhost;Port=3306;Database=students;";
            MySqlConnection con = new MySqlConnection(url);
            con.Open();
            //2.要拿到要发送的sql语句
            string sql = "select *from student where name='kobe'";
            MySqlCommand com = new MySqlCommand(sql, con);
            // 3 执行 sql 语句
            MySqlDataReader reader = com.ExecuteReader();
            reader.Read();// Read() 每次调用 都会从结果集中返回一行数据
            //reader.GetInt32(0);
            Console.WriteLine(reader.GetInt32(0));
            con.Close();
            ////对数据库进行  增  删  改  查
            ////1 拿到数据库的连接 并打开连接
            //string url = "User ID=root;Password=root;Host=localhost;Port=3306;Database=students;";
            //MySqlConnection con = new MySqlConnection(url);
            //con.Open();
            //string sql = "insert into student values(11,'hahahaha','man',6)";//添加信息
            //MySqlCommand cmd = new MySqlCommand(sql, con);
            //int result = cmd.ExecuteNonQuery();
            //Console.WriteLine("数据库打开结果:"+result);
            //con.Close();
 public static bool FindStudent(string name)
        {
            bool b = false;
            string url = "User ID=root;Password=root;Host=localhost;Port=3306;Database=students;";
            MySqlConnection con = new MySqlConnection(url);
            con.Open();
            string sql = "select *from studnet where name='{0}' ";
            sql = string.Format(sql, name);
            // Console.WriteLine(sql);
            MySqlCommand cmd = new MySqlCommand(sql, con);
            MySqlDataReader reader = cmd.ExecuteReader();
            b = reader.Read();
            return b;
        }

 

你可能感兴趣的:(c#mysql操作)