Google
 

Thursday, March 20, 2008

Inserting Data into a Database using OleDb

This snippet is shows you a simple way to insert data into a database using OleDb.

protected void Button1_Click(object sender, EventArgs e)
{
//Setup Connection string
String cnstr= "Provider=type in OLE DB Provider;server=type in IP address;
+ "Uid=type in database user;Pwd=type in database password;"
+ "database=type in database
name;"

//Create a new OleDbConnection
OleDbConnection cn = new OleDbConnection(cnstr);

//Create a SQL insert statement
//Don't forget to concatenate when using TextBox1.Text
String insert = "INSERT INTO table name (column name) VALUES ('"+ TextBox1.Text + "')";

//Create a new OleDbCommand
OleDbCommand insertcmd = new OleDbCommand (insert, cn);

//Open the connection
cn.Open();

//Execute the Query
insertcmd.ExecuteNonQuery();

//Close the connection
cn.Close();
}

*Quick Note: Don't forget to add 'using System.Data.OleDb;' to the top of the code behind page.

In your .aspx page add the following code in between the body tags. Click on the image to view full size.

If you have any questions or there are discrepancies in the code please feel free to leave a comment and I will try to answer/fix them as soon as I can.

1 comments:

Anonymous said...

tnx
:)