返回首页
当前位置: 主页 > 网络编程 > .Net实例教程 >

.net访问MySQL数据库程序代码

时间:2011-05-24 14:10来源:知行网www.zhixing123.cn 编辑:麦田守望者

1.使用ODBC.NET
ODBC.NET(全称ODBC .NET Data Provider)是一个免费的.NET Framework附加组件,需要到微软公司的网站上去下载,下载地址为:http://download.microsoft.com/download/dasdk/Install/1.0.4030.0/W98NT42KMeXP/EN-US/odbc_net.msi,它需要系统已经安装MDAC 2.7或者更高版本。另外,还需要安装MySQL的ODBC驱动程序,下载地址为:http://www.mysql.com/downloads/api-myodbc-2.50.html,
try{
string constr = "DSN=MySQL;" + "UID=;" +"PWD=";
conn = new OdbcConnection(constr);
conn.Open();
string query = "insert into test.dbtable values10,'disksidkfsdi', 'asdfaf', 'adsfasdf')";
string tmp = null;
OdbcCommand cmd = new OdbcCommand(query, conn);
for(int i = 0; i < 100000; i++)
{
cmd.ExecuteNonQuery();
}
cmd.Dispose();
conn.Close();
query = "select * from test.dbtable";OdbcCommand cmd2 = newOdbcCommand(query, conn);
conn.Open();OdbcDataReader reader = cmd2.ExecuteReader();
while(reader.Read()){tmp = reader[0].ToString();tmp = reader[1].ToString();tmp = reader[2].ToString();tmp = reader[3].ToString();}
conn.Close();
query = "delete from test.dbtable";OdbcCommand cmd3 = newOdbcCommand(query, conn);conn.Open();cmd3.ExecuteNonQuery();}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally{conn.Close();}

2. 使用MySQLDriverCS
MySQLConnection conn = null;
Try
{string connstr = "Data Source=MySQL;Password=root;User ID=root;Location=localhost";
conn = new MySQLConnection(constr);
conn.Open();
string query = "insert into test.dbtable values(10, 'disksidkfsdi', 'asdfaf', 'adsfasdf')";
string tmp = null;
MySQLCommand cmd = new MySQLCommand(query, conn);
for(int i = 0; i < 100000; i++){cmd.ExecuteNonQuery();}
cmd.Dispose();
conn.Close();
query = "select * from test.dbtable";MySQLCommand cmd2 = new MySQLCommand(query, conn);
conn.Open();
MySQLDataReader reader = cmd2.ExecuteReaderEx();while(reader.Read()){tmp = reader[0].ToString();tmp = reader[1].ToString();tmp = reader[2].ToString();tmp = reader[3].ToString();}
conn.Close();
query = "delete from test.dbtable";MySQLCommand cmd3 = new MySQLCommand(query, conn);
conn.Open();
cmd3.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Finally
{conn.Close();
}

------分隔线----------------------------
标签(Tag):C# C#实例教程 c#基础教程 C#源代码
------分隔线----------------------------
推荐内容
猜你感兴趣