使用C#express通过ODBC连接到MySQL数据库
问题描述:
我需要通过C#express 2008连接到MySQL数据库。我想我的代码与连接字符串分开。我从一个论坛获得这个代码,但连接字符串是SQLExpress 2005.可以有人请帮助我如何解决这个问题?下面是与SQL Express的连接字符串代码:使用C#express通过ODBC连接到MySQL数据库
//string connectionString = "Driver={SQL Native Client}; Server=localhost\\sqlexpress;" + "Database=oshahsdb;Trusted_Connection=yes;";
using (OdbcConnection odbcCon = new OdbcConnection(connectionString))
using (OdbcCommand odbcCom = new OdbcCommand("Select * FROM Product", odbcCon))
using (OdbcDataAdapter odbcDA = new OdbcDataAdapter(odbcCom))
using (DataSet ds = new DataSet())
{
odbcCon.Open();
odbcDA.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];
}
我还需要用户名和密码添加到连接字符串。
答
查看下面的MySQL Connector for .NET是一个发现的例子here。
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;pwd=12345;database=test;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
答
你真的需要使用ODBC连接吗?
如果可以,我建议使用MySQL Connector/Net。它是一个完全托管的提供商,并且是为.NET开发的,而ODBC driver更通用。
(当然,无论您选择如何连接,您仍然需要一个合适的连接字符串。)