Wednesday, 22 August 2012

SQL Sever 2005 Database connection in C# using class

Global class for Database connection and query execution, when create object for this class Database connection will be connected and execute(string query) used for query execution. 


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace LsiM
{
    class Subbiah
    {     
        SqlConnection con;
        SqlCommand com;

        public Subbiah()
        {
            con = new SqlConnection("data source=.;initial catalog=Lims;user id=sa;pwd=123"); //lims : Database Name
            try
            {
                con.Open();
            }
            catch
            {
               MessageBox.Show("-----Please Check Database Connection-------", "Connection Failed !!!!..", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        ~Subbiah()
        {
            if (con.State != ConnectionState.Open)
            {
                con.Close();
            }
        }

        public DataSet execute(string str)
        {
            com = this.con.CreateCommand();
            com.CommandText = str.ToString();
            com.CommandType = CommandType.Text;
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(com);
            da.Fill(ds);
            return ds;
        }
   
    }
}
   

No comments:

Post a Comment