C# 和 MySQL/Connector 5.2
一篇关于如何使用 Connector/NET 5.2 连接到 MySQL 数据库的文章
引言
我是一名初级 C# 开发者,在寻找一篇解释如何使用 Connector/NET 5.2 连接到 MySQL 数据库的“如何做”文章时遇到了很多困难。
所以,这里有一篇简单的文章解释如何做到这一点。
背景
要理解代码,你需要了解数据库技术。
我已经安装并运行了 MySQL 5 和 Connector/NET 5.2。
我创建了一个名为“cart
”的数据库,其中包含一个名为“members
”的表,该表包含字段“fname
”和“lname
”。
在 Visual Studio 2005 中,我创建了一个 consoleApp
。
然后,我将 Mysql.Data
提供程序添加到引用文件夹。
理解提供程序对象
MySql.Data
|
|--MySql.Data.MySqlClient
| |--MySqlCommand
| |--MySqlConnection
| |--MySqlDataAdapter
| |--MySqlDataReader
| |--MySqlException
| |--MySqlParameter
| |--MySqlDbType
| |--MySqlError
| |--MySqlHelper
| |--MySqlScript
|--MySql.Data.Types
你可以使用 Visual Studio 2005 中的对象浏览器查看提供程序的全部内容。
Using the Code
该代码使用 C# 和 Visual Studio 2005 进行测试。
using System;
using System.Collections.Generic;
using System.Text;
using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
//Set up connection string
string connString = @"
server = localhost;
database = cart;
user id = root;
password =;
";
//Set up query string
string sql = @" select * from members ";
MySqlConnection conn = null;
MySqlDataReader reader = null;
try
{
//open connection
conn = new MySqlConnection(connString);
conn.Open();
//Execute the Query
MySqlCommand cmd = new MySqlCommand(sql, conn);
reader = cmd.ExecuteReader();
//Display output header
Console.WriteLine("This program demonstrates the use of"
+ "the MYSQL Server Data Provider");
Console.WriteLine("Querying the database {0} with {1}\n"
, conn.Database
, cmd.CommandText
);
Console.WriteLine("{0} | {1}"
,"Firstname".PadLeft(10)
,"Lastname".PadLeft(10)
);
//Process the result set
while (reader.Read())
{
Console.WriteLine("{0} | {1}"
, reader["fname"].ToString().PadLeft(10)
, reader["lname"].ToString().PadLeft(10)
);
}
}
catch (Exception e)
{
Console.WriteLine("Error " + e);
}
finally
{
reader.Close();
conn.Close();
}
}
}
}
要测试,只需使用 Ctrl + F5 组合键即可。
关注点
作为一名初级开发者和写作新手,我不得不参考了一些资料。
一本关于 C# 和 SSE 的好书是“Beginning C# 2005 Databases”。
历史
- 2008 年 3 月 22 日:初始发布