Create and Connect to an SQLite database in C#

Hello guiz this tutorial is to teach you how to create a new SQLite database from scratch, create a new table in it, insert and read values from it. This is merely an entry level example to give you an idea on how to start. First you will need System.Data.SQLite library from system.data.sqlite.org. Head over to their download section and download the libraries that best suit your need depending on the .NET Framework you want to target and the Windows bit version.
Finally, the snippet below should give you the general idea on the main functions you will need to learn first, mainly.
Creating a file for your database Creating a table in your database Inserting information in the database Retrieving information from the database
  1. string createTableQuery = @"CREATE TABLE IF NOT EXISTS [MyTable] (
  2. [ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  3. [Key] NVARCHAR(2048) NULL,
  4. [Value] VARCHAR(2048) NULL
  5. )";
  6.  
  7. System.Data.SQLite.SQLiteConnection.CreateFile("databaseFile.db3");
  8. using (System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection("data source=databaseFile.db3"))
  9. {
  10. using (System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con))
  11. {
  12. con.Open();
  13.  
  14. com.CommandText = createTableQuery;
  15. com.ExecuteNonQuery();
  16.  
  17. com.CommandText = "INSERT INTO MyTable (Key,Value) Values ('key one','value one')";
  18. com.ExecuteNonQuery();
  19. com.CommandText = "INSERT INTO MyTable (Key,Value) Values ('key two','value value')";
  20. com.ExecuteNonQuery();
  21.  
  22. com.CommandText = "Select * FROM MyTable";
  23.  
  24. using (System.Data.SQLite.SQLiteDataReader reader = com.ExecuteReader())
  25. {
  26. while (reader.Read())
  27. {
  28. Console.WriteLine(reader["Key"] + " : " + reader["Value"]);
  29. }
  30. }
  31. con.Close();
  32. }
  33. }
ResultAnd the output will be.
  1. key one : value one
  2. key two : value value

Add new comment