加载中

Introduction

This article shows you how to connect to a MySQL database using the MySQL Connector for .NET. I will also show you how you can update MySQL database records using C#.

Prerequisites

  • Install Visual Studio 2008 or Visual Studio 2010
  • Install MySQL database on your local machine
  • MySQL database admin tool that allows you to create a database and run SQL statements. I am using phpMyAdmin which is a web interface.
  • Download and install MySQL Connector.

Getting Started

Run the XAMPP application and it will automatically install Apache server, MySQL database, and FileZilla. After installing check whether these services are running or not. The following XAMPP control panel shows which of those services are currently running.

简介

这篇文章将向你介绍通过 MySQL Connector for .NET 来连接到 MySQL 数据库,然后我们将向你展示如何使用 C# 更新 MySQL 数据库记录。

环境准备

  • 安装 Visual Studio 2008 或者 Visual Studio 2010
  • 在本机上安装 MySQL 数据库,当然你也可使用其他机器上已经装好的 MySQL 数据库
  • MySQL 数据库管理工具可以让你创建数据库和运行 SQL 语句,这里我们使用 phpMyAdmin
  • 下载并安装 MySQL Connector.

开始

运行 XAMPP 程序将自动为你安装 Apache 、MySQL 和 FileZilla。安装完毕后检查服务器是否运行,下图所示的 XAMPP 控制面板显示了当前正在运行的服务。

Now the following steps will show how to connect to a MySQL database using C#.

Step 1

Open MySQL Admin page and create a new database.

Step 2

After creating the new database, create a new table.

Step 3

After creating the new table, open Visual Studio and click on New Project and name the project. It will open the new project, then click on Solution Explorer (F4), right click on “Reference” to add a new reference into the project. Reference those two .dll files to the project (MySql.dll (Win apps), MySql.web.dll (Web apps)).

Step 4

Add namespace to the project.

Step 5

Create a MySQL connection string.

Step 6

The following code will insert the data into MySQL table.

Step 7

The following function will load the data from the table and bind it into a GridView.

Step 8

The final result is shown on the window form:

下面的步骤展示如何通过 C# 连接到 MySQL。

Step 1

在 phpMyAdmin 打开 MySQL 管理页然后创建新数据库

Step 2

创建完数据库后紧接着创建一个名为 PhoneBook 的表:

Step 3

接下来我们打开 Visual Studio 然后创建新项目,点击 Solution Explorer (F4), 在 “Reference” 节点上右键加入新的引用,这里我们需要引用两个 dll 文件到项目中,分别是:(MySql.dll (Win apps),MySql.web.dll (Web apps)).

Step 4

添加命名空间到项目中

Step 5

创建一个 MySQL 连接字符串

Step 6

下面代码将插入数据到表中:

Step 7

下面函数从表中加载数据并显示在 GridView 中:

Step 8

最终的 Windows Form 结果:

返回顶部
顶部