简单的数据库连接问题..
写了个类.
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);
SqlDataReader dr = Comm.ExecuteReader();
if (dr.Read())
{
Response.Write( "aa ");
Response.End();
}
}
}
}
错误:
编译器错误信息: CS1502: 与“System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)”最匹配的重载方法具有一些无效参数
源错误:
行 20: con.Open();
行 21: string sql = "select * from mc_ad ";
行 22: SqlCommand Comm = new SqlCommand(sql, con);
行 23: SqlDataReader dr = Comm.ExecuteReader();
行 24: if (dr.Read())
22行,为什么不能把CON直接给SQLCOMMAND用...
[解决办法]
SqlCommand Comm = new SqlCommand(sql, con);
这错了
你的con 是MC_Sql的实例
用 con.Conn
[解决办法]
MC_Sql是一个class,
SqlCommand(string, System.Data.SqlClient.SqlConnection)
的第二个参数要求是一个SqlConnection实例.
按你的代码,应该改为:
SqlCommand Comm = new SqlCommand(sql, con.Conn);