C# connect and use MySQL database detailed tutorial

C# connect to MySQL need to add a reference to connect to MySQL

本文将介绍3种添加MySQL引用的方法,以及连接MySQL和使用MySQL的教程

C# quotes MySQL steps:

the first method:

  1. Download mysql.data.dll
  2. Place the file in the project directory
  3. In the VS2019 project, refer to the mysql.data.dll file and
    enter the DLL official website to download the mysql.data.dllfile ( 可自选版本下载),
    Insert picture description here
    click download to
    Insert picture description here
    complete the download, then unzip the mysql.data.dllfile
    Insert picture description here
    and right-click in the project to reference -> add reference -> browse -> select the MySql.Data.dllfile -> OK. The operation is as follows:

Select reference

Insert picture description here

Right-click and click Add Reference

Insert picture description here

Click to browse

Insert picture description here

Choose the mysql.data.dllstorage path

Insert picture description here

After adding the reference, click OK

记住勾选dll文件
Insert picture description here
Click on the reference, you can see that the mysql.datareference has been added ( 引用属性里可以看到引用详细信息) the
Insert picture description here
second method

  1. Add dynamic link library file: download connector/net on the official website
  2. Place the file in the project directory
  3. In the VS2019 project, reference the mysql.data.dll file

Go to MySQL official website to download the dynamic link library file

Click Download
Insert picture description here
Click to No thanks, just start my download.start downloading
Insert picture description here
Double click the program
Insert picture description here
Click Next
Insert picture description here

Choose installation type

The following is the description of the three installation types:
Typical>Typical: usually install the most common program functions. Recommend to most users.
Custom>Customization: Allow users to choose which program features will be installed and where they will be installed. It is recommended for advanced users.
Complete>Complete: All program functions will be installed. The most disk space is required.

一般选择第一个Typical即可。

Insert picture description here
Click install to install,
Insert picture description here
see the progress bar, and wait for the installation.
Insert picture description here
The installation is complete
Insert picture description here

Select reference

Insert picture description here

Right-click and click Add Reference

Insert picture description here

mysql.data.dllDefault storage path

Since we installed the dynamic link library file, go directly to the C drive and select the dynamic link library file
path : C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.23\Assemblies\v4.5.2
you can see a lot of dynamic link library files.
Insert picture description here
Of course, you can also use mysql.data.dllthe file path that Everything quickly locates .
Insert picture description here
Input mysql.data.dllcan quickly locate
Insert picture description here

Continue with the steps you just added the reference! ! !

Click to browse

Insert picture description here

Choose the mysql.data.dllstorage path

Find the dll file path : C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.23\Assemblies\v4.5.2
click Add to
Insert picture description here
check, click OK to
Insert picture description here
view the reference. The
Insert picture description here
third method:
直接在visual studio内添加mysql方案包
select in the menu bar, 工具
Insert picture description here
click NuGet包管理器(N)
Insert picture description here
click 管理解决方案的NuGet程序包(N).Insert picture description here
enter, mysql
Insert picture description here
select the official ( 作者Oracle), check the item,
Insert picture description here
click install,
Insert picture description here
click OK ( 添加成功后会弹窗提示),
Insert picture description here
click I accept the
Insert picture description here
installation is successful
Insert picture description here

After completing the above operations, you can connect to the database through the code.

C# uses MySQL

Use usingto call the mysqlconnection, so that the connection can be automatically closed after use to connect
to the database, and there is no need to manually write a method to close the database.

Import namespaceusing MySql.Data.MySqlClient;
Insert picture description here

  • data source= Server IP address;
  • database= Database name;
  • user id= Database user name;
  • password= Database password;
  • pooling= Whether to put in the connection pool;
  • charset= Encoding method;

Parameters for
string connectstring= "data source=localhost;database=test1;user id=root;password=root;pooling=true;charset=utf8;";
connecting to the database: the method of connecting to the database:
MySqlConnection msc = new MySqlConnection(connectstring);

//导入命名空间
using MySql.Data.MySqlClient;

static void Main(string[] args)
        {
    
    
            //定义mysql连接字符串
            string constring = "data source=localhost;database=test1;user id=root;password=root;pooling=true;charset=utf8;";
            //连接mysql
            MySqlConnection msc = new MySqlConnection(constring);
        }

Detailed analysis of MySQL connection string parameters

Usually the database connection string is:

Database=dbname;Data Source=192.168.1.1;Port=3306;User Id=root;Password=****;Charset=utf8;TreatTinyAsBoolean=false;

parameter Description
Server,host, data source, datasource, address, addr, network address Database location (any of the above keywords can be used)
Database,initial catalog data storage name
Port socket port, default 3306
ConnectionProtocol,protocol Connection protocol, default Sockets
PipeName , pipe Connection pipeline, default MYSQL
UseCompression,compress Whether the connection is compressed, the default is false
AllowBatch Whether to allow multiple SQL statements to be executed at one time, the default is true
Logging Whether to enable the log, the default is false
SharedMemoryName The name of the memory share, default MYSQL
UseOldSyntax,old syntax, oldsyntax Is it compatible with the old version of the syntax, the default is false
ConnectionTimeout,connection timeout Connection timeout waiting time, default 15s
DefaultCommandTimeout,command timeout MySqlCommand timeout time, the default is 30s
UserID, uid, username, user name, user Database login account
Password,pwd login password
PersistSecurityInfo Whether to keep sensitive information, the default is false
Encrypt Encrypt
CertificateFile Certificate file (.pfx) format
CertificatePassword Certificate password
CertificateStoreLocation Where to store the certificate
CertificateThumbprint Certificate fingerprint
AllowZeroDateTime Whether the date and time can be zero, the default is false
ConvertZeroDateTime Whether the zero date and time are converted to DateTime.MinValue, the default is false
UseUsageAdvisor, usage advisor Whether to enable the assistant, it will affect the performance of the database, the default is false
ProcedureCacheSize,procedure cache, procedurecache Several stored procedures can be cached at the same time, 0 is forbidden, the default is 25
UsePerformanceMonitor,userperfmon, perfmon Whether to enable performance monitoring, the default is false
IgnorePrepare Whether to ignore the Prepare() call, the default is true
UseProcedureBodies,procedure bodies Whether to check the validity of the stored procedure body and parameters, the default is true
AutoEnlist Whether to automatically use the active connection, the default is true
RespectBinaryFlags Whether to respond to the binary flag of the metadata on the column, the default is true
TreatTinyAsBoolean Whether to treat the TINYINT(1) column as a boolean, the default is true
AllowUserVariables Whether to allow user variables to appear in SQL, the default is false
InteractiveSession,interactive Whether the session allows interaction, the default is false
FunctionsReturnString Whether all server functions are processed according to the return string, the default is false
UseAffectedRows Whether to replace the number of rows found with the number of affected rows to return data, the default is false
OldGuids Whether to use the binary(16) column as Guids, the default is false
Keepalive The number of seconds to keep the TCP connection, the default is 0, not keep.
ConnectionLifeTime The minimum time (in seconds) that the connection remains in the connection pool before being destroyed. Default 0
Pooling Whether to use thread pool, default true
MinimumPoolSize, min pool size The minimum number of threads allowed in the thread pool, the default is 0
MaximumPoolSize,max pool size The maximum number of threads allowed in the thread pool, the default is 100
ConnectionReset Whether to automatically reset after the connection expires, the default is false
CharacterSet, charset The character set used to request the connection from the server, default: none
TreatBlobsAsUTF8 Whether binary blobs are treated as utf8, the default is false
BlobAsUTF8IncludePattern The matching mode of the column. Once matched, it will be processed as utf8. Default: none
SslMode Whether to enable SSL connection mode, default: MySqlSslMode.None

SQL command execution method:

ExcuteNonQuery执行增改删

  1. insert(increase)
  2. updata(change)
  3. delete(delete)

ExcuteReader: Execute a multi-line query and return the DataReader object
ExcuteScalar: execute a single-line query and return the first row of data in the query result
Create a MySQLcommand object: MySqlCommand cmd = new MySqlCommand(sql, msc);
read a DataReadersingle row of object data: reader.Read()
get a single row of field data: reader.GetInt32(0); reader.GetString(1);**

//导入命名空间
using MySql.Data.MySqlClient;

static void Main(string[] args)
        {
    
    
            //定义mysql连接字符串
            string constring = "data source=localhost;database=test1;user id=root;password=root;pooling=true;charset=utf8;";
            //连接mysql
            MySqlConnection msc = new MySqlConnection(constring);
             #region MySQL操作
        //写入sql语句
        string sql = "select * from user";
        //创建命令对象
        MySqlCommand cmd = new MySqlCommand(sql, msc);
        //打开数据库连接
        msc.Open();
        //执行命令,ExcuteReader返回的是DataReader对象
        MySqlDataReader reader = cmd.ExecuteReader();
        //循环单行读取数据,当读取为null时,就退出循环
        while (reader.Read())
        {
    
    
            //输出第一列字段值
            Console.Write(reader.GetInt32(0) + "\t");
            //Console.Write(reader.GetInt32("id") + "\t");

            //判断字段"username"是否为null,为null数据转换会失败
            if (!reader.IsDBNull(1))
            {
    
    
                //输出第二列字段值
                Console.Write(reader.GetString(1) + "\t");
                //Console.Write(reader.GetString("username") + "\t");
            }
            //判断字段"password"是否为null,为null数据转换会失败
            if (!reader.IsDBNull(2))
            {
    
    
                //输出第三列字段值
                Console.Write(reader.GetString(2) + "\n");
                //Console.Write(reader.GetString("password") + "\t");
            }
        }
    }
   
   			 Console.ReadKey();
        }

Guess you like

Origin blog.csdn.net/qq_31762741/article/details/115032697