Jan 7, 2014

C# SQL Server Connection -Secure & Best

To Create A Highly Secure SqlServer Connection We Must Have Connection String and All The Sql Stuff In Separate Class...
Without Doing Anything Related SQL Stuff  In The Current Class We Can Create A Separate Class For That And We Can Handle From Their...

Create A New Class Call DBConnect and Paste The Following Code
This Class Controls All The Sql Related Stuff

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;


namespace MyProject
{
    class DBConnect
    {
        string strconnection= "Server=localhost;Database=dbname;Trusted_Connection=True;";
        SqlConnection sqlcon = new SqlConnection();
        SqlCommand sqlcmd = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();

        public void connect()
        {
            sqlcon = new SqlConnection(strconnection);
            sqlcon.Open();
        }
       
        public void disconnect()
        {
            if (sqlcon.State == ConnectionState.Open)
            {
                sqlcon.Close();
                sqlcon.Dispose();
            }
        }
       
        public DataTable ReadData(string query)
        {
            try
            {
                connect();
                sqlcmd = new SqlCommand(query, sqlcon);
                da = new SqlDataAdapter(sqlcmd);
                dt = new DataTable();
                da.Fill(dt);          
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                disconnect();
            }
            return dt;
        }
    
        public void QryCommand(string query)
        {
            try
            {
                connect();
                sqlcmd = new SqlCommand(query, sqlcon);
                sqlcmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                disconnect();
            }
        }
    }
}


We  Can Use Following Codes To Do Changes In The Database


1.Insert Data

string query = "INSERT INTO ur_table VALUES('value1','value2')";
DBConnect dbc = new DBConnect();
dbc.connect();
dbc.QryCommand(query);


2.Get Single Data

string query = "SELECT * FROM ur_table";
DBConnect dbc = new DBConnect();
dbc.connect();
DataTable dt = new DataTable();
dt = dbc.ReadData(query);
foreach (DataRow row in dt.Rows)
{
       txtName.Text = row[0].ToString();
}

No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...