To Create the DataBase Connectin locally with the sql server using c#.net some steps need to be follow .
But Before establish the connection with the database the sql server need to be configured .
Steps to connect with sql server is given below Given below:
- Import the SqlClient
library using the syntax-> using
System.Data.SqlClient;
- create the object of the
sqlConnection as scn;
3.open the connection using
scn.Open();
- Create and run the Database
Query.
- Close the connection
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 connectivity_using_sql
{
public partial class Form1 : Form
{
SqlCommand scommand; SqlDataReader dr;
SqlDataReader srdr;
SqlConnection scn;
string str;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
scn=new SqlConnection ("server=mysqlservername-5ed77e1\\sqlexpress;Integrated Security=true;database=master");
}
private void InsertButton_Click(object sender, EventArgs e)
{
scn.Open();
str="insert into employee values('"+textBox1 .Text +"','"+textBox2.Text +"')";
scommand =new SqlCommand (str,scn );
scommand .ExecuteNonQuery ();
MessageBox.Show("ok");
scn.Close();
}
private void SearchButton_Click(object sender, EventArgs e)
{
scn.Open();
str="select * from employee where empid='"+textBox1 .Text +"'";
scommand = new SqlCommand(str, scn);
dr = scommand.ExecuteReader();
if (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
else
MessageBox.Show("not Found");
scn.Close();
}
private void DeleteButton_Click(object sender, EventArgs e)
{
scn.Open();
str = "delete from employee where empid='"+textBox1 .Text +"'";
scommand = new SqlCommand(str, scn);
int n=scommand.ExecuteNonQuery();
if (n > 0)
MessageBox.Show("Delete Success");
else
MessageBox.Show("Error");
scn.Close();
}
private void UpdateButton_Click(object sender, EventArgs e)
{
scn.Open();
str = "update employee set empname='"+textBox2.Text +"' where empid='" + textBox1.Text + "'";
scommand = new SqlCommand(str, scn);
int n = scommand.ExecuteNonQuery();
MessageBox.Show("'" + n + "'");
if (n > 0)
MessageBox.Show("update Success");
else
MessageBox.Show("Error");
scn.Close();
}
}
}
0 Comment(s)