DNN and Mysql .Net Connector
今天尝试了一下,在DNN的模式一下,部分模块采用mysql存储数据,而主DNN依然运行在Sql Server下。
步骤如下:
1.在web.config增加连接:
<add
name="SiteMySqlServer"
connectionString="Server=192.168.69.159;Port=3306;Database=Demo;Uid=root;Pwd="
providerName="System.Data.SqlClient" />
*providerName -- 不用管。
主要是connectionString,目前很奇怪,无法在里面加charset,一加后,mysql connector就报错。
2. 引入mysql connector <详细:http://dev.mysql.com/downloads/connector/net/6.0.html> ,最新版是6.0
3.在自己的dnn module中引入mysql.data,我们主要用的类是:MySqlHelper.
相关实例代码如下,里面包含了直接使用sql语句,调用存储过程,是否带参数等方式。如果需要使用事务,尽量使用存储过程模式,MySqlHelper好像无法直接支持事务操作。
Code
public override IDataReader GetUserList()
{
MySqlParameter param1 = new MySqlParameter();
param1.Value = "xxx";
param1.ParameterName = "name";
MySqlParameter param2 = new MySqlParameter();
param2.Value = 20;
param2.ParameterName = "age";
//return MySqlHelper.ExecuteReader(_connectionString, "select * from test where name=@name and age=@age " ,new MySqlParameter[]{param1,param2});
return MySqlHelper.ExecuteReader(_connectionString, "call test_sp_getuser (@name,@age) ", new MySqlParameter[] { param1, param2 });
}
public override IDataReader GetUserList()
{
MySqlParameter param1 = new MySqlParameter();
param1.Value = "xxx";
param1.ParameterName = "name";
MySqlParameter param2 = new MySqlParameter();
param2.Value = 20;
param2.ParameterName = "age";
//return MySqlHelper.ExecuteReader(_connectionString, "select * from test where name=@name and age=@age " ,new MySqlParameter[]{param1,param2});
return MySqlHelper.ExecuteReader(_connectionString, "call test_sp_getuser (@name,@age) ", new MySqlParameter[] { param1, param2 });
}
4.实体类(PO),
一般情况,我们使用 CBO.FillCollection<UserInfo>(DataProvider.Instance().GetUserList()); 来填充数据,但是实际测试下情况下,这种方式不行。
为了支持这种方式,我们必须在UserInfo类中实现IHydratable接口,实例代码如下:
Code
public class UserInfo : IHydratable
{
public int Id;
public string Name;
public int Age;
#region IHydratable 成员
public void Fill(System.Data.IDataReader dr)
{
Id = Convert.ToInt32(Null.SetNull(dr["Id"], Id));
Name = Convert.ToString(Null.SetNull(dr["name"], Name));
Age = Convert.ToInt32(Null.SetNull(dr["age"], Age));
}
public int KeyID
{
get
{
return Id;
}
set
{
Id = value;
}
}
#endregion
}
public class UserInfo : IHydratable
{
public int Id;
public string Name;
public int Age;
#region IHydratable 成员
public void Fill(System.Data.IDataReader dr)
{
Id = Convert.ToInt32(Null.SetNull(dr["Id"], Id));
Name = Convert.ToString(Null.SetNull(dr["name"], Name));
Age = Convert.ToInt32(Null.SetNull(dr["age"], Age));
}
public int KeyID
{
get
{
return Id;
}
set
{
Id = value;
}
}
#endregion
}
story is over....
enjoy yourself.