Tuesday, 3 April 2012

Update data in SQL Server databse

In this post I am going to retrieve data from database and then update the information in the database. To do you need to follow the following steps:

1. Create a form as shown below



2. Code to update data

//Code for GET DATA button
private void btnGetData_Click(object sender, EventArgs e)
{
    //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 = comboBoxEmployee.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
    txtName.Text = name;
    dateTimePicker1.Text = birthdate;
    txtAddress.Text = address;
    txtEmail.Text = email;
    txtPhone.Text = phone;
    comboBoxJobTitle.Text= jobtitle;

    connection.Close();
}

//code for UPDATE button
private void btnUpdate_Click(object sender, EventArgs e)
{
    //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  update data
    string sql = "UPDATE Employees SET Name='" + txtName.Text + "', BirthDate='" + dateTimePicker1.Text + "', Address='" + txtAddress.Text + "', Email='" + txtEmail.Text + "', Phone='" + txtPhone.Text + "', JobTitle='" +comboBoxJobTitle.Text +"' WHERE Name=@Name";
    SqlCommand cmd = new SqlCommand(sql, connection);
    SqlParameter param = new SqlParameter();
    param.ParameterName = "@Name";
    param.Value = comboBoxEmployee.Text;
    cmd.Parameters.Add(param);
    cmd.CommandType = CommandType.Text;
    int result = cmd.ExecuteNonQuery();

    //check if record has been updated in the database
    if (result > 0)
        MessageBox.Show("Record Updated!");
    else
        MessageBox.Show("Failed to update!");

    connection.Close();
}

No comments:

Post a Comment