电商总结(三)构建数据库的主从架构
时间:2021-07-01 10:21:17
帮助过:4人阅读
<summary>
/// 根据数据库的语句,选择相应的DB
/// </summary>
/// <param name="sql"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static DB SelectDB(
string sql, CommandType commandType)
{
bool redirect2WritableDB =
false;
sql = sql.Trim().TrimStart(
‘\r‘).TrimStart(
‘\n‘);
if (sql.IndexOf(
"UPDATE", StringComparison.OrdinalIgnoreCase) >=
0)
redirect2WritableDB =
true;
if (sql.IndexOf(
"DELETE", StringComparison.OrdinalIgnoreCase) >=
0)
redirect2WritableDB =
true;
if (sql.IndexOf(
"INSERT", StringComparison.OrdinalIgnoreCase) >=
0)
redirect2WritableDB =
true;
if (sql.IndexOf(
"CREATE", StringComparison.OrdinalIgnoreCase) >=
0)
redirect2WritableDB =
true;
if (sql.IndexOf(
"ALTER", StringComparison.OrdinalIgnoreCase) >=
0)
redirect2WritableDB =
true;
//// 如果是存储过程,则默认是取Writable DB。
if (redirect2WritableDB || commandType ==
CommandType.StoredProcedure)
{
return DBConfiguration.WritableDB;
}
else
{
int random =
GenerateRandomNumber();
int dbIndex = random %
DBConfiguration.ReadDBs.Count;
return DBConfiguration.ReadDBs[dbIndex];
}
}
同时,增加相关的数据库配置
<?xml version="1.0" encoding="utf-8" ?>
<ConnectionString>
<WritableDB>Data Source=192.168.99.242; Initial Catalog=DBTest; Uid=sa;pwd=test123; MultipleActiveResultSets=True</WritableDB>
<ReadDBs>
<DB>Data Source=192.168.99.241; Initial Catalog=DBTest; Uid=sa;pwd=test123; MultipleActiveResultSets=True</DB>
</ReadDBs>
</ConnectionString>
电商总结(三)构建数据库的主从架构
标签: