ConnectionString 属性尚未初始化 求助高手
源错误:行 53:
行 54: DataSet products = new DataSet();
行 55: sqlAdapter1.Fill(products, "products");
行 56:
行 57: return products;
源文件: D:\bookshop\components\productsdb.cs 行: 55
下面是productsdb.cs源文件 大家帮忙看看什么错误啊 我是个新手 郁闷中
using System;
using System.Data;
using System.Data.SqlClient;
namespace book
{
/// <summary>
/// productsdb 的摘要说明。
/// </summary>
public class productsdb
{
string m_ConnectionString;
public productsdb(string dsn)
{
//
// TODO: 在此处添加构造函数逻辑
//
m_ConnectionString=dsn;
}
public DataSet GetProduct(string productCode)
{
SqlConnection sqlConnection = new SqlConnection(m_ConnectionString);
SqlDataAdapter sqlAdapter1;
if(productCode=="")
sqlAdapter1 = new SqlDataAdapter("SELECT * FROM Products ", sqlConnection);
else
sqlAdapter1 = new SqlDataAdapter("SELECT * FROM Products WHERE ProductCode='"+productCode+"'", sqlConnection);
DataSet products = new DataSet();
sqlAdapter1.Fill(products, "products");
return products;
}
public DataSet GetProducts(string category)
{
SqlConnection sqlConnection = new SqlConnection(m_ConnectionString);
SqlDataAdapter sqlAdapter1 = new SqlDataAdapter("SELECT * FROM Products WHERE ProductType='"+category+"'", sqlConnection);
DataSet products = new DataSet();
sqlAdapter1.Fill(products, "products");
return products;
}
public DataSet GetProductCategories()
{
SqlConnection sqlConnection = new SqlConnection(m_ConnectionString);
SqlDataAdapter sqlAdapter1 = new SqlDataAdapter("SELECT Distinct ProductType FROM Products", sqlConnection);
DataSet products = new DataSet();
sqlAdapter1.Fill(products, "products");
return products;
}
}
}
--------------------编程问答-------------------- SqlConnection sqlConnection = new SqlConnection(m_ConnectionString);
连接串在哪里赋值了?
--------------------编程问答-------------------- string m_ConnectionString;
m_ConnectionString 連接字串没有赋值吧
一般将连接串放到webcofig中 --------------------编程问答-------------------- 连接字符串的问题
但不同意楼上的说法
一个简单的例子吧,如果我要频繁的换数据库连接字符串,那么我要频繁的控制去读web.config
应该是将某一模块下操作相同数据库的方法写到一起,这些方法有着相同的数据库连接字符串,也就是说我读的时候只读这个模块下的connection
--------------------编程问答-------------------- 你的连接放在webconfig里但是没有附给string m_ConnectionString;啊
using System;
using System.Data;
using System.Data.SqlClient;
namespace book
{
/// <summary>
/// productsdb 的摘要说明。
/// </summary>
public class productsdb
{
string m_ConnectionString = ConfigurationManager.ConnectionStrings["名称"].ConnectionString;
public productsdb(string dsn)
{
//
// TODO: 在此处添加构造函数逻辑
//
m_ConnectionString=dsn;
}
public DataSet GetProduct(string productCode)
{
SqlConnection sqlConnection = new SqlConnection(m_ConnectionString);
--------------------编程问答-------------------- lz是通过构造器的参数来给m_ConnectionString赋值 ,m_ConnectionString 在类被实例化时被赋值
productsdb db=new productsdb("server=.;uid=sa;pwd=sa;database=northwind"); --------------------编程问答-------------------- <add key="sqlconn" value="uid=sa;pwd=123456;server=192.168.1.10;database=test;"/>
补充:.NET技术 , ASP.NET