first add
using System.Data;
using System.Data.SqlClient;
import statements at the top of the code page.
Then copy the following functions to your code:
public static SqlConnection GetConnection(string strConn)
{
SqlConnection conn=null;
try
{
conn = new SqlConnection(strConn);
conn.Open();
}
catch (SqlException ex)
{
Console.Write("SQL ERROR: " + ex.Message);
}
catch (Exception ex)
{
Console.Write("ERROR: " + ex.Message);
}
return conn;
}
public int ExecuteNonQuery(string strConn,string query)
{
SqlConnection conn = GetConnection(strConn);
int result=0;
SqlCommand cmd = new SqlCommand(query, conn);
try
{
//Configure the SqlCommand object
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
//Set type to StoredProcedure
cmd.CommandText = query;
result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.Write("Error running a query " + query + ": " + ex.Message);
}
finally
{
conn.Close();
}
return result;
}
And then do the following:
string query="INSERT INTO Table1(Field1,Field2)VALUES("test","test2");
string strConn="Your database connection string here";
int output=ExecuteNonQuery(strConn,query);
if output=0 the insert failed, otherwise succeeded.
If you are dealing with access database, use the same functions but replace SqlConnection and SqlCommand with OleDbConnection and OleDbCommand