1.web.config 读取数据
<add name="SqlConnection" connectionString="server=192.168.1.100;uid=a;pwd=a;database=person" providerName="MySQLProv"/>
2.读取数据库的公共方法
public static string ConnectionString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
/// <summary>
/// 建立数据库联接
/// </summary>
/// <returns></returns>
public MySqlConnection getconn()
{
MySqlConnection myconn = new MySqlConnection(ConnectionString);
return myconn;
}
/// <summary>
///执行SqlCommand
/// </summary>
/// <param name="M_Str_sqlstr"></param>
public MySqlCommand getcom(string M_Str_sqlstr)
{
MySqlConnection myconn = this.getconn();
myconn.Open();
MySqlCommand sqlcom = new MySqlCommand(M_Str_sqlstr, myconn);
sqlcom.ExecuteNonQuery();
//sqlcom.Dispose();
//myconn.Close();
//myconn.Dispose();
return sqlcom;
}
public DataSet getds(string M_str_sqlstr, string M_str_table)
{
MySqlConnection myconn = getconn();
myconn.Open();
MySqlDataAdapter sqlda = new MySqlDataAdapter(M_str_sqlstr, myconn);
DataSet myds = new DataSet();
sqlda.Fill(myds, M_str_table);
return myds;
}
public MySqlDataReader getread(string M_str_sqlstr)
{
MySqlConnection myconn = this.getconn();
MySqlCommand mycmd = new MySqlCommand(M_str_sqlstr, myconn);
myconn.Open();
MySqlDataReader mysqlread = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
return mysqlread;
}
3.读取
如:查询
//查询sql
String sqlSearch = "select * from a";
MySqlCommand mySqlCommand = getcom(sqlSearch);
try
{
using (MySqlDataReader reader = mySqlCommand.ExecuteReader())
{
IList<Systemaccount> list = GetListFromReader(reader);
if (list.Count > 0)
{
return list[0];
}
}
}
catch (Exception ex)
{
//Log Error here;
}
return null;
不过最后设置完以后,出现“Host 'localhost' is not allowed to connect to this MySQL server”
1.首先停止mysql服务,在控制面板---管理工具--服务里面
直接把mysql数据库下的user表中的host字段为“localhost”的值修改为“%”就可以了
可是我改完之后没有效果,我上网搜索了各种解决方案都不行,一开始我没把服务停止,后来把服务停止后就可以了,不知道是不是这个原因,希望大侠们指点
参照的连接 http://www.blogjava.net/acooly/archive/2008/09/17/229368.html