C#连接Mysql数据库详细教程(内附Mysql及Navicat)

  using System;

  using System.Collections.Generic;

  using System.Linq;

  using System.Text;

  using MySql.Data.MySqlClient;

  namespace DataBaseManager

  {

  class connect

  {

  public MySqlConnection conn = null;//连接对象

  public MySqlCommand comm = null;//语句执行对象

  public MySqlDataReader dr = null;//语句执行结果数据对象

  //用于一个窗口让用户自定义输入用户名与密码,在这里我直接定义好了

  //public string uid;

  //public string pwd;

  public void load()

  {

  //直接写链接语句,比较容易出错

  //conn = new MySqlConnection(

  // "Database = data;Server = localhost;Port = 3306;Password = " + pwd + ";UserID = " + uid + ";charset = utf8mb4");

  //conn.Open();

  //使用Builder写语句,实现分段

  //与数据库连接的信息

  MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();

  //数据库连接时的用户名,可以用pid

  builder.UserID = "root";

  //数据库连接时的密码,可以用pwd

  builder.Password = "admin";

  //数据库连接时的服务器地址

  builder.Server = "localhost";

  //要连接的数据库

  builder.Database = "data";

  //定义与数据连接的链接

  conn = new MySqlConnection(builder.ConnectionString);

  //打开这个链接

  conn.Open();

  }

  }

  }