// Author: Tigran Gasparian
// This sample is part Part One of the 'Getting Started with SQLite in C#' tutorial at
[Link]
using System;
using [Link];
namespace SQLiteSamples
{
class Program
{
// Holds our connection with the database
SQLiteConnection m_dbConnection;
static void Main(string[] args)
{
Program p = new Program();
}
public Program()
{
createNewDatabase();
connectToDatabase();
createTable();
fillTable();
printHighscores();
}
// Creates an empty database file
void createNewDatabase()
{
[Link]("[Link]");
}
// Creates a connection with our database file.
void connectToDatabase()
{
m_dbConnection = new SQLiteConnection("Data Source=[Link];Version=3;");
m_dbConnection.Open();
}
// Creates a table named 'highscores' with two columns: name (a string of max 20 characters)
and score (an int)
void createTable()
{
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
[Link]();
}
// Inserts some values in the highscores table.
// As you can see, there is quite some duplicate code here, we'll solve this in part two.
void fillTable()
{
string sql = "insert into highscores (name, score) values ('Me', 3000)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
[Link]();
sql = "insert into highscores (name, score) values ('Myself', 6000)";
command = new SQLiteCommand(sql, m_dbConnection);
[Link]();
sql = "insert into highscores (name, score) values ('And I', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
[Link]();
}
// Writes the highscores to the console sorted on score in descending order.
void printHighscores()
{
string sql = "select * from highscores order by score desc";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = [Link]();
while ([Link]())
[Link]("Name: " + reader["name"] + "\tScore: " + reader["score"]);
[Link]();
}
}
}