MySQL Connector/NET
外觀
項目上添加對MySQL.Data的引用
[編輯]在C#項目的Solution Explorer的References上,右鍵菜單選擇Add References...,在Assemblies->Extensions的列表中選中"MySQL.Data"。
C#示例
[編輯]using System;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
public class Tutorial1
{
public static void Main()
{
string connStr = "server=localhost;user=root;database=world;port=3306;password=******";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
// Perform database operations
string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent='Oceania'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0] + " -- " + rdr[1]);
}
rdr.Close();
sql = "INSERT INTO Country (Name, HeadOfState, Continent) VALUES ('Disneyland','Mickey Mouse', 'North America')";
cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "SELECT COUNT(*) FROM Country";
cmd = new MySqlCommand(sql, conn);
object result = cmd.ExecuteScalar();
if (result != null)
{
int r = Convert.ToInt32(result);
Console.WriteLine("Number of countries in the world database is: " + r);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Console.WriteLine("Done.");
}
}
ASP.NET示例
[編輯]using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using MySql.Data;
using MySql.Data.MySqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string constr = "server=localhost;user=root;database=world;port=3306;password=";
string constr = ConfigurationManager.ConnectionStrings["localMySQL"].ConnectionString.ToString();
MySqlConnection con = new MySqlConnection(constr);
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from city", con);
MySqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
con.Close();
}
}