Tuesday, January 7, 2014

SQL Query Class

SQL Query Class just add it to yourz code and call its methods through class object refrance and pass parameters of yourz SQL Database path and SQL query to implement on database. This Whole code is in C# .................................................................



using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;

namespace IMS
{

    class SQLClass
    {

        public void Conect(string AddQuery, string Path)
        {
            SqlConnection con = new SqlConnection(Path);
            con.Open();
            SqlCommand com = new SqlCommand(AddQuery, con);
            var RowEfected = com.ExecuteNonQuery();
            con.Close();
            if (RowEfected > 0)
            {
                MessageBox.Show("Data Saved Successfully");
            }
            else
            {
                MessageBox.Show("Data Not Saved");
            }
        }

        public int DataReadrint(string AddQuery, string Path)
        {
            int Num=0;
            SqlConnection con = new SqlConnection(Path);
            con.Open();
            SqlCommand com = new SqlCommand(AddQuery, con);
            SqlDataReader sdr = com.ExecuteReader();
            while (sdr.Read())
            {
               Num = sdr.GetInt32(0);
            }
            con.Close();
            return Num;
        }

        public string DataReadrstring(string AddQuery, string Path)
        {
            string Word="a";
            SqlConnection con = new SqlConnection(Path);
            con.Open();
            SqlCommand com = new SqlCommand(AddQuery, con);
            SqlDataReader sdr = com.ExecuteReader();
            while (sdr.Read())
            {
                Word = sdr.GetString(0).ToString();
            }
            con.Close();
            return Word;
        }

    }
}

We Use this class on our C# app like that :::::::

SQLClass sq = new SQLClass();
string AQ = string.Format("Select I_Id From Items Where (I_Name='" + cmbx_R_IName.Text + "')");
            int IID = sq.DataReadrint(AQ, path);


Here first method is to simply do insertion in database and the second method is to get an integer value from data base and return it as an integer value . third one is the same method like second but just the change is, its for an string type data to get from data base and use is on yourz form app or on any console app....................

No comments:

Post a Comment