Tehrik-e-Insaaf

Earn 600$ by Clicking on each Ad

GoWellUp.com

Wednesday, October 22, 2008

How to Insert Data in Database in c#

1. First of all make connection string
string connString="Data Source=databasename;Initial Catalog=Test;User ID=sa;Password=sa;"
SqlConnection conn = new SqlConnection(connString);

2. Open the connection
conn.Open();

3. Write the insert command
string insertCommand= @"insert into dbo.compDetails(OwnerId, compName, compAddress, compPhone) values('" + compId + "','" + this.txtCompaName.Text + "','" + this.txtCompAddress.Text + "','" + this.txtCompPhone.Text + "')";

SqlCommand cmdInsert = new SqlCommand(insertCommand, conn);

4. Execute the command
cmdInsert.ExecuteScalar();

5. Close the connection
conn.Close();


Example:

public void setData()
{

string connString="Data Source=databasename;Initial Catalog=Test;User ID=sa;Password=sa;"
SqlConnection conn = new SqlConnection(connString);
conn.Open();
Guid compId = Guid.NewGuid();
string insertCommand= @"insert into dbo.compDetails(OwnerId, compName, compAddress, compPhone) values('" + compId + "','" + this.txtCompaName.Text + "','" + this.txtCompAddress.Text + "','" + this.txtCompPhone.Text + "')";
SqlCommand cmdInsert = new SqlCommand(insertCommand, conn);
cmdInsert.ExecuteScalar();
conn.Close();

}

No comments: