Friday, 30 March 2012

Save & Retrive Data to/from sql server database

In this post I am going to show two main things:
1. How to save data in the database
2. How to retrieve data back from the database

I am doing this in a simple and very easy way. To save and retrieve data first you should create a table with required fields. Lets us now first see how to save data into the database.

Save data into database

1. Create a form as shown below


2. Code for ADD button

try
{
//create database connection
string connectionString = "Data Source=abc;
    Initial Catalog=abc;User ID=abc;Password=abc";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

//sql statement to insert employee information in database
string sql = "INSERT INTO Employees 
    (Name, BirthDate, Address, Email, Phone, JobTitle) 
    VALUES (@Name, @BirthDate, @Address, @Email, @Phone, @JobTitle)";

//code to insert into database
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@BirthDate", dateTimePicker.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@JobTitle", comboBox.SelectedItem);
cmd.CommandType = CommandType.Text;
int result = cmd.ExecuteNonQuery();

//check if record has been added to the database
if (result > 0)
    MessageBox.Show("Record Added!");
else
    MessageBox.Show("Failed to add!");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}


Retrieve data from database

1. Create a form as shown below


 2. Code for SEARCH button
 
//create database connection
string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

//sql query to retrive data from database
string sql = "SELECT * FROM Employees WHERE Name = @Name";
SqlCommand cmd = new SqlCommand(sql, connection);
SqlParameter param = new SqlParameter();
param.ParameterName = "@Name";
param.Value = comboBox1.SelectedValue;
cmd.Parameters.Add(param);
SqlDataReader dr = cmd.ExecuteReader();
string name = " " ;
string birthdate = " ";
string address = " ";
string email = " ";
string phone = " ";
string jobtitle = " ";
while (dr.Read())
{
    name = dr.GetValue(1).ToString();
    birthdate = dr.GetValue(2).ToString();
    address = dr.GetValue(3).ToString();
    email = dr.GetValue(4).ToString();
    phone = dr.GetValue(5).ToString();
    jobtitle = dr.GetValue(6).ToString();
}
dr.Close();

//displaying retrieved data
lblDisplayName.Text = name;
lblDisplayBirthDate.Text = birthdate;
lblDisplayAddress.Text = address;
lblDisplayEmail.Text = email;
lblDisplayPhone.Text = phone;
lblDisplayJobTitle.Text = jobtitle;

 3. Following is the form with the data retrieved from database