ADO包装器类C# [英] ADO Wrapper Class C#

查看:91
本文介绍了ADO包装器类C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我想将我的代码转换为包装器类,这样我就可以从所有项目中调用它,而不必继续重复它.

这是我现在的代码的一部分.我想包装打开的连接,DataTable

Hi Everyone,
I want to convert my code to wrapper class so i can call it from all the project, and don''t need to keep repeat it .

this is part of my code right now. i want to wrap the open connection ,DataTable

protected void Page_Load(object sender, EventArgs e)
    {
        this.Master.HighlightMenu = "Customers";
        //Declare the connection object
        SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyLocal"].ConnectionString);

        //Make the connection 
        Conn.Open();

        //Define you query
        string sql = "SELECT * FROM Customer Order by LastName, FirstName";

        //Declare a SQL Adapter
        SqlDataAdapter da = new SqlDataAdapter(sql, Conn);

        //Declare a DataTable
        DataTable dt = new DataTable();

        //Populate the DataTable
        da.Fill(dt);

        //Bind the Listview
        lv.DataSource = dt;
        lv.DataBind();

        dt.Dispose();
        da.Dispose();
        Conn.Close();
    }



我尝试过那样,但我不知道它是否正确或如何从任何页面调用它.



I tried like that but i don''t know if it right or how to call it from any page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public class DB
{
    private SqlConnection sqlConn; 
	public DB()
	{
	}
public void OpenConnection()
{
    if (sqlConn == null)
    {
      sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyLocal"].ConnectionString);
           sqlConn.Open();
    }
	
	else 
	{
		 sqlConn.Close();

	}

}

public DataTable RunQuery(string Sql)
{
    OpenConnection();
    
}

推荐答案

public class DB
    {
        public static SqlConnection Connect()
        {
            string connectionString = "Data Source=.;Initial Catalog = YourDatabaseName;uid =sa;pwd = YourPassword";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                // Do something
                return connection;
            }
            
            
        }
    }



很好的介绍这个主题:
http://msdn.microsoft.com/en-us/library/x9afc042.aspx [ ^ ]

http://msdn.microsoft.com/en-us/library/79b3xss3.aspx [ ^ ]

还有《 C#编程指南》的其余部分.

问候



Good introduction to this topic:
http://msdn.microsoft.com/en-us/library/x9afc042.aspx[^]

http://msdn.microsoft.com/en-us/library/79b3xss3.aspx[^]

And the rest of the C# Programming Guide.

Regards


可以在此处此处找到小示例 [ ^ ]


这篇关于ADO包装器类C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆