C# connect to MySQL need to add a reference to connect to MySQL
本文将介绍3种添加MySQL引用的方法,以及连接MySQL和使用MySQL的教程
C# quotes MySQL steps:
the first method:
- Download mysql.data.dll
- Place the file in the project directory
- In the VS2019 project, refer to the mysql.data.dll file and
enter the DLL official website to download themysql.data.dll
file (可自选版本下载
),
click download to
complete the download, then unzip themysql.data.dll
file
and right-click in the project to reference -> add reference -> browse -> select theMySql.Data.dll
file -> OK. The operation is as follows:
Select reference
Right-click and click Add Reference
Click to browse
Choose the mysql.data.dll
storage path
After adding the reference, click OK
记住勾选dll文件
Click on the reference, you can see that the mysql.data
reference has been added ( 引用属性里可以看到引用详细信息
) the
second method
- Add dynamic link library file: download connector/net on the official website
- Place the file in the project directory
- In the VS2019 project, reference the mysql.data.dll file
Go to MySQL official website to download the dynamic link library file
Click Download
Click to No thanks, just start my download.
start downloading
Double click the program
Click Next
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即可。
Click install to install,
see the progress bar, and wait for the installation.
The installation is complete
Select reference
Right-click and click Add Reference
mysql.data.dll
Default 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.
Of course, you can also use mysql.data.dll
the file path that Everything quickly locates .
Input mysql.data.dll
can quickly locate
Continue with the steps you just added the reference! ! !
Click to browse
Choose the mysql.data.dll
storage path
Find the dll file path : C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.23\Assemblies\v4.5.2
click Add to
check, click OK to
view the reference. The
third method:
直接在visual studio内添加mysql方案包
select in the menu bar, 工具
click NuGet包管理器(N)
click 管理解决方案的NuGet程序包(N).
enter, mysql
select the official ( 作者Oracle
), check the item,
click install,
click OK ( 添加成功后会弹窗提示
),
click I accept the
installation is successful
After completing the above operations, you can connect to the database through the code.
C# uses MySQL
Use using
to call the mysql
connection, 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;
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执行增改删
:
insert
(increase)updata
(change)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 MySQL
command object: MySqlCommand cmd = new MySqlCommand(sql, msc);
read a DataReader
single 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();
}