Click here to Skip to main content
15,891,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to make a class for sql connection and data adapter so i can use it in all the site without repeating it all the time, also i have a problem with calling it from the page. sorry i am new in ado.net.
I made the connection and it works fine ,but i don't think it's the best way to make it.
C#
public static SqlConnection OpenConnection()
    {
      
        SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyLocal"].ConnectionString);

       try
        {
            sqlConn.Open();
            
            sqlConn.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);

           
        }
            
        return sqlConn;
    }

data adapter
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

/// <summary>
/// Summary description for DB
/// </summary>
public class DB
{
   // private SqlConnection sqlConn; 
	public DB()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public static DataSet DataReader(DataSet dataset,
     string connectionString, string queryString)
    {
        using (SqlConnection connection =
            new SqlConnection(ConfigurationManager.ConnectionStrings["MyLocal"].ConnectionString;))
        {
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = new SqlCommand(
                queryString, connection);
            adapter.Fill(dataset);
            return dataset;
        }
    }

HERE IS MY CODE IN OTHER PAGE
C#
public partial class Idea : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Master.HighlightMenu = "Customers";

        
      // Open Connection
      //  DB.OpenConnection();
        DB.OpenConnection();
        
           
            string sql = "SELECT * FROM Customer Order by LastName, FirstName";

            //Declare a SQL Adapter
            SqlDataAdapter da = new SqlDataAdapter(sql, DB.OpenConnection());

            //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();
            DB.OpenConnection().Close();}
Posted
Updated 4-Apr-12 7:56am
v3
Comments
ZurdoDev 4-Apr-12 13:53pm    
You would throw the exception so that whoever is calling it can handle it.

1 solution

Why recreate the wheel? Data Access Application Block[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900