database connection c# code example
Example 1: sqlite connection c#
using System.Data.SQLite;
SQLiteConnection.CreateFile("TestDB.db3")
SQLiteConnection conn = new SQLiteConnection(@"data source = TestDB.db3");
conn.Open();
SQLiteCommand cmd = new SQLiteCommand("create table table1 (username TEXT, password TEXT)", conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Enter the username");
string UserName = Console.ReadLine();
Console.WriteLine("Enter Password");
string PassWord = Console.ReadLine();
SQLiteCommand cmd2 = new SQLiteCommand("insert into table1 (username, password) values ('"+Username+"', '"+PassWord+"')", conn);
cmd2.ExecuteNonQuery();
Example 2: sql connection c#
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Example 3: create class for database connection in c#
public static class SqlDBHelper
{
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (SqlException ex)
{
}
return ds;
}
}
public static DataTable ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (SqlException ex)
{
}
return ds.Tables[0];
}
}
}