请教一个数据库连接类的调用方法
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace myDbMang
{
/// <summary>
///
/// </summary>
public abstract class DbManagerSQL
{
//数据库连接字符串(web.config来配置)
//<add key="ConnectionString" value="server=127.0.0.1;database=DATABASE;uid=sa;pwd=" />
protected static string connectionString = ConfigurationSettings.AppSettings["ConnectionString"];
public DbManagerSQL()
{
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param >查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
ds.Clear();
connection.Open();// 出错位置:提示 ConnectionString 属性尚未初始化。
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
}
=================================================
在自己的页面调用
public class ListCG : DbManagerSQL
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string sqlStr = "select CGName from SqlDbf";
DataSet CgDs = ListCG.Query(sqlStr);
if (CgDs.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = CgDs;
GridView1.DataBind();
}
else
{
Label2.Text = "没有相关记录";
}
}
==========================================================
connection.Open();// 出错位置:提示 ConnectionString 属性尚未初始化。
那个数据库类是我在网上找的代码,请问这个类应该怎么样调用,我调用的写法是不是写错了?还是这个数据库连接类本身代码有问题?
[解决办法]
错误提示指向这里:
protected static string connectionString = ConfigurationSettings.AppSettings["ConnectionString"];
你得看看有没有在config配置文件中加上ConnectionString的配置。
[解决办法]
web.config 里打错了吧,最好不要写静态的,写成这样好:
protected string connectionString
{
get
{
return ConfigurationSettings.AppSettings["ConnectionString"];
}
}