本文章是建立在已经安装MySQL数据库的前提,默认安装在C:\Program Files (x86)\MySQL,建议在安装时选中Connector.NET 6.9的安装,里面有MySQL与C#连接的动态链接库。
帮助文档C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation\ConnectorNET.chm是我撰写此文章的主要依据。其中Users Guide下,Programming是对动态链接库8个类的介绍,Tutorial是案例代码。
连接数据库、操作数据库,本质是利用数据库提供的动态链接库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.
1.添加动态链接库文件
方法一:Visual Studio,在 项目(右键)-管理NuGet程序包(N) 然后在浏览里面搜索MySql.Data并进行安装。
方法二:安装数据库MySQL时要选中Connector.NET 6.9的安装,将C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies里v4.0或v4.5中的MySql.Data.dll添加到项目的引用。v4.0和v4.5,对应Visual Studio具体项目 属性-应用程序-目标框架 里的.NET Framework的版本号。