C# connect to database


C# connect to MySQL database

  This article is based on the premise that the MySQL database has been installed. It is installed in C:\Program Files (x86)\MySQL by default. It is recommended to select the installation of Connector.NET 6.9 during installation, which contains a dynamic link library for MySQL and C# connection.

  The help document C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation\ConnectorNET.chm is my main basis for writing this article. Among them, under the Users Guide, Programming is an introduction to the 8 classes of the dynamic link library, and Tutorial is the case code.

  The essence of connecting to the database and operating the database is to use the dynamic link library MySql.Data.dll provided by the database to operate. MySql.Data.dll provides the following 8 classes:

  • MySqlConnection: Connect to MySQL server database.
  • MySqlCommand: Execute a sql statement.
  • MySqlDataReader: Contains the result of sql statement execution and provides a method to read a row from the result.
  • MySqlTransaction: Represents a SQL transaction in a MySQL database.
  • MySqlException: Exception returned when MySQL reports an error.
  • 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.

1. Add dynamic link library file

  Method 1: Visual Studio, in Project (Right Click) - Manage NuGet Packages (N) and then search for MySql.Data in Browse and install it.

  Method 2: Select the installation of Connector.NET 6.9 when installing the database MySQL, and add MySql.Data.dll in v4.0 or v4.5 in C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies A reference to the project. v4.0 and v4.5 correspond to the version number of the .NET Framework in the Visual Studio specific project properties - application - target framework.

2. Establish a connection (MySqlConnection class)

复制代码
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 represents the local machine, the port number The default port is 3306, you can not write MySqlConnection conn = new MySqlConnection(connetStr); try { conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句 Console.WriteLine("已经建立连接"); //在这里使用代码对数据库进行增删查改 } catch (MySqlException ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); }
复制代码

3.捕捉异常(MySqlException类)

  连接错误时MySqlConnection会返回一个MySqlException,其中包括2个变量:

  Message: A message that describes the current exception.

  Number: The MySQL error number. (0: Cannot connect to server. 1045: Invalid user name and/or password.)

复制代码
catch (MySqlException ex)
{
    switch (ex.Number)
    {
        case 0:
        Console.WriteLine("Cannot connect to server.  Contact administrator");
        break;
    case 1045:
        Console.WriteLine("Invalid username/password, please try again");
        break;
    }
}            
复制代码

4.增删查改的代码(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判断。执行失败不返回任何数据,报错,下面代码都不执行

 5.事务(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();
    }
}
复制代码

   

  结语:连接数据库、操作数据库,本质是利用数据库提供的动态链接库MySql.Data.dll进行操作。动态链接库中的8个类上面常用操作只用到了类1-5,类6-8 的相关操作未涉及, 大家可以去看帮助文档C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation\ConnectorNET.chm学习。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324581318&siteId=291194637