database connection c# code example

Example 1: sqlite connection c#

//Download "System.Data.Sqlite" from "Manage Nuget Packages" Section
using System.Data.SQLite;
SQLiteConnection.CreateFile("TestDB.db3") //Create a Database
SQLiteConnection conn = new SQLiteConnection(@"data source = TestDB.db3"); //Establish a connection with our created DB
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)
            {
                //log to a file or Throw a message ex.Message;
            }
            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)
            {
                //Show a message or log a message on ex.Message
            }
            return ds.Tables[0];
        }
    }   
}