Generic Code - Insert a record into the database using C# code

Karthikanbarasan
Posted by Karthikanbarasan under Sql Server category on | Points: 40 | Views : 3873
    private const string constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data source =";
private string dbName;
private string constring;

public int InsertDatatoDB(string sqlCommandString)
{
int flag = 1;
OleDbConnection myDBObj = new OleDbConnection();
OleDbCommand command;

constring = constring + dbName;

try
{
myDBObj.ConnectionString = constring;
myDBObj.Open();
command = new OleDbCommand(sqlCommandString, myDBObj);
command.ExecuteNonQuery();
}
catch (Exception ex)
{
flag = 0;
}
finally
{
myDBObj.Close(); // Close it
}
return flag;
}

Comments or Responses

Posted by: T.saravanan on: 1/24/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Karthik,

Some corrections are there in your code.
*Give the namespace details of OLEDB Conection. [using System.Data.OleDb].
* Two times using the same string object [constring]

Finally my suggestion is pass the sample dbName and Command String into your code.Its very useful to the beginners.





Posted by: Karthikanbarasan on: 1/24/2011 Level:Silver | Status: [Member] [Moderator] [Microsoft_MVP] [MVP] | Points: 10
Hi Saravanan...

Thanks for your suggestions...
Posted by: T.saravanan on: 1/24/2011 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Karthik,

My Suggestion is correction in your code .Kindly correct those changes in your code.

Login to post response