mysql的sqlhelper,可以切换数据库的SqlHelper

一个项目我一般只用一个数据库,现在有需求,需要使用多个数据库,临时改了一下,不知道好不好,请高手指教,大家使用多数据库的时候是如何切换的。

DBHelper.cs

Copy to Clipboard

e2bccdbad7bc28f4ef2a8fa52a21e480.gif引用的内容:[www.veryhuo.com]

private static string connectionString = "SQLCONNECTIONSTRING";

///

///

public static void SetSqlConnection(string connStr)

{

connectionString = connStr;

}

///

///

public static String GetSqlConnection()

{

String conn = ConfigurationManager.AppSettings[connectionString].ToString();

return conn;

}

///

///SQL语句

///参数对象数组

///

public static int ExecuteSql(String Sqlstr, SqlParameter[] param)

{

String ConnStr = GetSqlConnection();

using (SqlConnection conn = new SqlConnection(ConnStr))

{

SqlCommand cmd = new SqlCommand();

cmd.Connection = conn;

cmd.CommandText = Sqlstr;

cmd.Parameters.AddRange(param);

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

return 1;

}

}

Test.cs(BLL)

Copy to Clipboard

aa627a6b0d9a89f22bcea6370439fcec.gif引用的内容:[www.veryhuo.com]

using System;

using System.Collections.Generic;

using System.Linq;

using System.Data;

using System.Configuration;

using System.Web;

using HY.Common;

using System.Text;

using System.Data.SqlClient;

namespace HY.BLL

{

public class Test

{

///

static Test()

{

DBHelper.SetSqlConnection("SQLCONNECTIONSTRING");

}

///

///

public static DataTable getAll()

{

StringBuilder sb = new StringBuilder();

sb.Append("select * from t_Users");

return DBHelper.ExecuteDt(sb.ToString());

}

///

///

public static DataTable getTable()

{

DBHelper.SetSqlConnection("SQLCONNECTIONSTRING1");//BLL中这样切换

StringBuilder sb = new StringBuilder();

sb.Append("select * from t_User");

return DBHelper.ExecuteDt(sb.ToString());

}

}

}

web.config

Copy to Clipboard

aa627a6b0d9a89f22bcea6370439fcec.gif引用的内容:[www.veryhuo.com]

SqlTest.aspx.cs

Copy to Clipboard

aa627a6b0d9a89f22bcea6370439fcec.gif引用的内容:[www.veryhuo.com]

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

Bind();

}

private void Bind()

{

//切换数据库的操作封装在BLL中

GridView1.DataSource = Test.getAll();

GridView1.DataBind();

//切换数据库

GridView2.DataSource = Test.getTable();

GridView2.DataBind();

}

完整代码:/Files/greatverve/MyFiles.rar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值