写了个类.
public class MC_Sql
{
public SqlConnection Conn=null;
public MC_Sql()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 建立数据库连接
/// </summary>
public void Open()
{
Page NewPage = new Page();
string Sql_Path = ConfigurationSettings.AppSettings[ "MCDB "];//建立数据库连接字符串
if (Conn == null)
{
Conn = new SqlConnection(Sql_Path);
}
if (Conn.State == ConnectionState.Closed)
{
try
{
Conn.Open();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
}
finally
{
}
}
}
}
在外面调用
public partial class _Default : System.Web.UI.Page
{
MC_Sql con = new MC_Sql();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
con.Open();
string sql = "select * from mc_ad ";
SqlCommand Comm = new SqlCommand(sql, con);