MySQL是一款常用的关系型数据库管理系统,而C#是一种常用的面向对象程序设计语言。在项目开发和实践应用中,C#和MySQL常常一起使用。本文将介绍在C#中如何使用MySQL数据库。
首先,需要使用MySQL Connector/NET连接器。该连接器是MySQL官方提供的与Visual Studio等IDE合作开发的工具。在Visual Studio中,选择“工具”-“NuGet包管理器”-“管理解决方案的NuGet程序包”,搜索并安装MySQL.Data。
连接数据库:
using MySql.Data.MySqlClient; MySqlConnection connection = new MySqlConnection("server=localhost;port=3306;database=数据库名;user=用户名;password=密码"); try{connection.Open();Console.WriteLine("已连接到数据库!");}catch (Exception ex){ Console.WriteLine(ex.ToString());}
执行SQL语句:
MySqlCommand command = connection.CreateCommand(); command.CommandText = "SELECT * FROM 表名"; MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader.GetString(0)+","+reader.GetString(1)); } reader.Close();
关闭数据库连接:
connection.Close();
本文对C#中使用MySQL数据库做了简单介绍,希望读者能够在项目开发中熟练使用该类库。