MySQL provides standards-based drivers for JDBC, ODBC, and .Net enabling developers to build database applications in their language of choice. In addition, a native C library allows developers to embed MySQL directly into their applications.
连接MYSQL数据库的方法及示例
方法一:
使用MYSQL推出的MySQL Connector/Net is an ADO.NET driver for MySQL
该组件为MYSQL为ADO.NET访问MYSQL数据库设计的.NET访问组件。
安装完成该组件后,引用命名空间MySql.Data.MySqlClient;
使用命令行编译时:csc /r:MySql.Data.dll test.cs
方法二:
通过ODBC访问MYSQL数据库
访问前要先下载两个组件:odbc.net和MYSQL的ODBC驱动(MySQL Connector/ODBC (MyODBC) driver)目前为3.51版
安装完成后,即可通过ODBC访问MYSQL数据库
方法三:
使用CoreLab推出的MYSQL访问组件,面向.NET
安装完成后,引用命名空间:CoreLab.MySql;
使用命令编译时:csc /r:CoreLab.MySql.dll test.cs
MySQL Connector/Net
Standard
Default port is 3306.
Specifying port
Named pipes
It is the port value of -1 that tells the driver to use named pipes network protocol. This is available on Windows only. The value is ignored if Unix socket is used.
Multiple servers
Use this to connect to a server in a replicated server configuration without concern on which server to use.
Using encryption
This one activates SSL encryption for all data sent between the client and server. The server needs to have a certificate installed.
This option is available from Connector/NET version 5.0.3. In earlier versions, this option has no effect.
Using encryption, alternative
Some reported problems with the above one. Try replacing the key "Encryption" with "Encrypt" instead.
这里我使用第一种方法进行示例,首先要到 http://www.mysql.com/downloads/connector/net/
//获得用户输入数据
string UserID = this.tbUserName.Text.Trim();
string UserPassword = this.tbPassword.Text.Trim();
//创建与数据库的链接
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Persist Security Info=False;database=UserInfo;server=localhost;Uid=root;pwd=xian80";
conn.Open();
//创建对数据库查询命令
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select UserName from Users where UserID ='" + UserID + "'and Password ='" + UserPassword+"'";
//对数据库进行查询,并将查询结果保存到数据阅读器dr中
MySqlDataReader dr;
dr = cmd.ExecuteReader();
//判断用户是否存在
if (count < 3)
{
if (dr.Read())
{
MessageBox.Show(dr.GetString(0).ToString() + "欢迎你!");
}
else
{
count++;
if (count < 3)
{
MessageBox.Show("用户名或密码错误,请重新输入!");
}
else
{
MessageBox.Show("您输入的次数已经超过三次,程序将关闭!");
this.Close();
}
}
}