如何在Clas Library C#中使用Ado.Net对象 [英] How Do I Use Ado.Net Objects In Clas Library C#
问题描述
我是类库的新手。我正在尝试为我的网站创建数据访问层但不能使用sqlcommand或任何其他ADO.net对象。
我的代码如下所示:
I am new to class library.I am trying to crate data access layer for my -tier website but not able to use sqlcommand or any other ADO.net object.
My code is like below:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
Using System.Configuration;
namespace TEST.DAL
{
public class AdminDAL
{
public static SqlConnection conn=new SqlConnection(ConfigurationManager"dbCon").ConnectionString));
SqlCommand cmd=new SqlCommand("sp_insert",conn);
...
...
}
}
现在我无法使用此cmd对象来声明参数或任何属性。即使在将sqlcommand变为静态后,cmd的intellisense也不会出现,因为我无法使用它。请帮助我。
...
...
}
}
Now i can not use this cmd object to declare parameters or any attributes.The intellisense for cmd also not coming even after decalring sqlcommand as static i could not be able to use it.Please help me .
推荐答案
首先,将您的逻辑包装在方法中。因为访问其他类中的功能需要whart。
示例 -
First of all, wrap your logic inside a method. Because that's whart is needed to access the functionality in other classes.
Example-
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
Using System.Configuration;
namespace TEST.DAL
{
public class AdminDAL
{
public static SqlConnection conn=new SqlConnection(ConfigurationManager"dbCon").ConnectionString));
public int ExecuteSPNonQuery()
{
SqlCommand cmd=new SqlCommand("sp_insert",conn);
. //rest of the logic here
现在,您应该可以使用类的实例访问此方法。
希望,它有帮助:)
Now, you should be able to access this method with the instance of the class.
Hope, it helps :)
更正后的代码:
corrected code:
public static SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["yourconnectionstringname"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_insert", conn);
note :不要在方法之外不必要地创建对象。
访问方法/函数中的 cmd
对象,你可以看到 intellisense
现在
SqlCommand
对象应该在方法中使用,除非它对整个模块是通用的。
note: dont create objects unnecessarily outside the methods.
Access the cmd
object inside a method/Function, you could able to see the intellisense
now
SqlCommand
object should be used inside the methods unless it is common to the entire module.
这篇关于如何在Clas Library C#中使用Ado.Net对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!