1. Install and reference
Install through NuGet package manager, Install-Package
2. Create a database
string dbFilename = ""; if (!(dbFilename)) { (dbFilename); }
3. Set the database password
string connectionString = ("Data Source={0};Version=3;",dbFilename); using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { ();//Open the database ("123456");//Set password}
4. Connect to the database
string connectionString =("Data Source={0}; Version=3; Password={1};",dbFilename,"123456"); using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { (); }
5. Create a table
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { (); string commandText = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(100), Code VARCHAR(100),Password VARCHAR(100))"; using (SQLiteCommand command = new SQLiteCommand(commandText, connection)) { ();//Execute sql } }
6. Add data
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { (); string commandText = "insert into Users (Name, Code,Password) values (@name, @code,@password)"; using (SQLiteCommand command = new SQLiteCommand(commandText, connection)) { // Set parameter values ("@name", "administrator"); ("@code", "admin"); ("@password", "123456"); // Execution statement (); } }
7. Modify the data
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { (); string commandText = "update Users SET Password=@password WHERE Code = @code"; using (SQLiteCommand command = new SQLiteCommand(commandText, connection)) { // Set parameter values ("@code", "admin"); ("@password", "admin123456"); // Execution statement (); } }
8. Query data
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { (); string commandText = "select * from Users"; using (SQLiteCommand command = new SQLiteCommand(commandText, connection)) { using (SQLiteDataReader reader = ()) { while (()) { ($"ID: {reader["Id"]}, name: {reader["Name"]}, coding: {reader["Code"]}"); } } } }
9. Delete data
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { (); string commandText = "delete from Users where Code = @code"; using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { // Set parameter values ("@code", "admin"); // Execution statement (); } }
The above is the detailed content of C# connecting to SQLite database and implementing basic operations. For more information about C# connecting to SQLite, please pay attention to my other related articles!