Skip to main content

How to connect to sql server to c# (.net ) using code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
    class query
    {
     public   SqlConnection con;

        SqlCommand cmd;
        public SqlDataReader sdr;

        public query()
        {
            con = new SqlConnection("Data Source=LAB1PC7\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True");

        }

        public int modify(string s)
        {
            con.Open();
            cmd = new SqlCommand(s, con);
            int r = cmd.ExecuteNonQuery();
            con.Close();
            return r;
        }

        public SqlDataReader select(string s)
        {
            con.Open();
            cmd = new SqlCommand(s, con);
            sdr = cmd.ExecuteReader();
            //con.Close();
            return sdr;

        }

    }

}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        query ab;
        public Form1()
        {
            InitializeComponent();
            ab =new query();

        }

     
        private void cmd_insert_Click(object sender, EventArgs e)
        {

          int r= ab.modify("insert into table11 values('"+txt_id.Text.Trim()+"','"+txt_name.Text.Trim()+"','"+txt_marks.Text.Trim()+"')");
          if (r > 0)
              MessageBox.Show("sucess");

        }

        private void cmd_select_Click(object sender, EventArgs e)
        {
            SqlDataReader dr = ab.select("select s_name,marks from table11 where id='"+txt_id.Text.Trim()+"'");
            if (dr.HasRows)
            {
                dr.Read();
                txt_marks.Text = dr[1].ToString();
                txt_name.Text = dr[0].ToString();
            }
            ab.sdr.Close();
            ab.con.Close();
        }

        private void cmd_update_Click(object sender, EventArgs e)
        {
            int r = ab.modify("update table11 set s_name ='" +  txt_name.Text.Trim() + "', marks ='" + txt_marks.Text.Trim() + "' where id ='"+txt_id.Text.Trim()+"'");
            if (r > 0)
                MessageBox.Show("sucess");
        }

    }

    }

Comments

Popular posts from this blog

unix commands