c#内sqllite代码案例
时间: 2023-07-02 11:18:12 浏览: 112
以下是一个使用C#和SQLite进行数据库操作的示例代码:
```csharp
using System.Data.SQLite;
//连接到数据库
SQLiteConnection connection = new SQLiteConnection("Data Source=myDatabase.db;Version=3;");
connection.Open();
//创建表格
string createTableQuery = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL)";
SQLiteCommand createTableCommand = new SQLiteCommand(createTableQuery, connection);
createTableCommand.ExecuteNonQuery();
//插入数据
string insertQuery = "INSERT INTO users (name, age) VALUES ('John', 25)";
SQLiteCommand insertCommand = new SQLiteCommand(insertQuery, connection);
insertCommand.ExecuteNonQuery();
//查询数据
string selectQuery = "SELECT * FROM users";
SQLiteCommand selectCommand = new SQLiteCommand(selectQuery, connection);
SQLiteDataReader reader = selectCommand.ExecuteReader();
while (reader.Read())
{
int id = Convert.ToInt32(reader["id"]);
string name = reader["name"].ToString();
int age = Convert.ToInt32(reader["age"]);
Console.WriteLine("ID: {0}, Name: {1}, Age: {2}", id, name, age);
}
//关闭连接
connection.Close();
```
此代码连接到名为myDatabase.db的SQLite数据库,创建一个名为users的表格并插入一行数据,然后查询并输出所有用户的信息。请注意,此示例仅用于演示目的,实际应用程序中需要更多的错误检查和异常处理。
阅读全文