c#+mysql类使用方法

更新时间:02-05 教程 由 暗香浮 分享

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数据库做了简单介绍,希望读者能够在项目开发中熟练使用该类库。

声明:关于《c#+mysql类使用方法》以上内容仅供参考,若您的权利被侵害,请联系13825271@qq.com
本文网址:http://www.25820.com/tutorial/14_2075547.html