1. Add, delete, change to the database
// Database file storage path, (Environment.CurrentDirectory: is the full path of the current working directory)
string dbPath = "Data Source =" + Environment.CurrentDirectory + "/test.db";
// Create a connection database instance, specify the file location
SQLiteConnection con = new SQLiteConnection (dbPath);
// Open the database, it will be created automatically if the file does not exist
con.Open ();
// Build table statement
string sql = "CREATE TABLE IF NOT EXISTS student (id integer, name varchar (20), sex varchar (2));";
// Create SQL execution instruction object
SQLiteCommand com = new SQLiteCommand (sql, con);
// If there are no parameters, use the following statement to assign
//com.CommandText = sql;
//com.Connection = con;
// Execute the SQL command to create a data table, if the table does not exist, create a data table
com.ExecuteNonQuery ();
// Add data to the table
// 1. Use sql statement to add line by line
com.CommandText = "INSERT INTO student VALUES (1,‘ Little Red ’,‘ Male ’)";
com.ExecuteNonQuery ();
com.CommandText = "INSERT INTO student VALUES (2,‘ Little Li ’,‘ Female ’)";
com.ExecuteNonQuery ();
com.CommandText = "INSERT INTO student VALUES (3,‘ 小 明 ‘,‘ 男 ’)";
com.ExecuteNonQuery ();
// 2. Add using transaction
// Instantiate a transaction object
SQLiteTransaction tran = con.BeginTransaction ();
// Assign the transaction object to the transaction attribute of com
com.Transaction = tran;
// Set sql statement with parameters
com.CommandText = "INSERT INTO student VALUES (@id, @name, @sex)";
for (int i = 0; i <10; i ++)
{
// Add parameters
com.Parameters.AddRange (new [] {// Add parameter
new SQLiteParameter ("@ id", i + 1),
new SQLiteParameter ("@ name", "test" + i),
new SQLiteParameter ("@ sex", i% 3 == 0? "Male": "Female")
});
// Perform addition
com.ExecuteNonQuery ();
}
// commit transaction
tran.Commit ();
// Close the database
con.Close ();
2. Read data
// Database path
string dbPath = "Data Source =" + Environment.CurrentDirectory + "/test.db";
// Create a database instance and specify the file location
SQLiteConnection conn = new SQLiteConnection (dbPath);
// Open the database, it will be created automatically if the file does not exist
conn.Open ();
// Query sql statement
string sql = "select * from student";
// Instantiate sql instruction object
SQLiteCommand cmdQ = new SQLiteCommand (sql, conn);
// Store the read value
SQLiteDataReader reader = cmdQ.ExecuteReader ();
// Controls to display data
richTextBox1.Text = "";
// Read each row of data
while (reader.Read ())
{
// Read and assign to the control
richTextBox1.Text + = reader.GetInt32 (0) + "" + reader.GetString (1) + "" + reader.GetString (2) + "\ n";
}
// Close the database
conn.Close ();
Simple use of sqlite under C #