- Course
- SQLite Databases
- Create database and tables
Create database and tables
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a C# program that creates a version 3 SQLite database with two tables (Person and Teacher). Use the SQL statements in the entry to create the tables.
To connect to SQLite open a new connection against the database file, then create a new command using the SQLiteCommand
object and finally run the command once for each table.
Remember that to connect to SQLite you will need the reference of System.Data.SQLite
, you can get it from official page or install it directly in your project using the Nuguet package manager, executing the following command in the console:
Install-Package System.Data.SQLite -Version 1.0.112
Input
create table if not exists person (name varchar(20), age int)
create table if not exists teacher (name varchar(20))
Output
Solution
using System.Data.SQLite;
using System.IO;
public class CreateDatabaseSQLite
{
public static string DatabaseFileName = "out.sqlite";
public static void Main(string[] args)
{
CreateDatabaseIfNotExists();
CreateTablesIfNotExists();
}
public static void CreateDatabaseIfNotExists()
{
if (!File.Exists(DatabaseFileName))
{
SQLiteConnection.CreateFile(DatabaseFileName);
}
}
public static void CreateTablesIfNotExists()
{
using (SQLiteConnection cnx =
new SQLiteConnection("Data Source=" + DatabaseFileName + ";Version=3;"))
{
cnx.Open();
string sqlTablePerson = "create table if not exists person (name varchar(20), age int)";
using (SQLiteCommand cmd = new SQLiteCommand(sqlTablePerson, cnx))
{
cmd.ExecuteNonQuery();
}
string sqlTableTeacher = "create table if not exists teacher (name varchar(20))";
using (SQLiteCommand cmd = new SQLiteCommand(sqlTableTeacher, cnx))
{
cmd.ExecuteNonQuery();
}
}
}
}