Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Create Connection C# with SQL Database

1. Create connection
2.
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

SqlConnection conn = new SqlConnection("Data Source=DESKTOP-


C71GJJC\\AMIN;Initial Catalog=PU;Integrated Security=True");
Or

SqlConnection conn = new SqlConnection("Data Source=");

3. Write insert code


SqlCommand cmd = new SqlCommand("insert into Std
values('"+textBox1.Text+"','"+textBox2.Text+"','"+comboBox1.Text+"','"+textBox3.Text
+"','"+comboBox2.Text+"')", conn);

try
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data was saved!");
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);

4. Write Update Code

SqlCommand cmd = new SqlCommand("Update Std set id='" + textBox1.Text +


"',Name='" + textBox2.Text + "',Gender='" + comboBox1.Text + "',Phone='" +
textBox3.Text + "',Dept='" + comboBox2.Text + "' Where id='"+textBox1.Text+"'",
conn);

try
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data was updated!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
5. Write Delete code

SqlCommand cmd = new SqlCommand("Delete from Std Where id=


('"+textBox1.Text+"')", conn);

try
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data was Deleted!");
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

6. Write DataGradeView code

void fillData()
{
SqlCommand cmd = new SqlCommand("Select * from std",conn);

try
{
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
sda.Fill(dt);
dataGridView1.DataSource = dt;
sda.Update(dt);

conn.Close();

}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

You might also like