你要知道的C#操作注册表知识都在这里了,C#添加、删除、检查注册表代码-C#-天下网吧
SQLite是微软专门为桌面程序开发的一款数据库,使用简单、方便、高效,很多C#项目使用的数据库引擎都是SQLite为原型。包括以后要讲到的使用C#开发网吧游戏菜单,采用的数据库也是SQLite。
本节讲解如何使用C#操作SQLite数据库。
创建一个基本的WnForm程序,取名为SqlLiteDemo,放入两个按钮button1和button2:
添加NuGet引用:
在流量里搜索
SQLite,找到System.Data.SQLite
下载安装即可自动添加了SQLite引用到项目中
然后双击button1和button2
复制以下代码替换原来的代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SQLite; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace SqlLiteDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //创建数据库 bool CreatDb() { string dbPath = "./test.db"; try { SQLiteConnection.CreateFile(dbPath); return true; } catch (Exception ex) { throw new Exception("新建数据库文件" + dbPath + "失败:" + ex.Message); } } //创建新表 static public void NewTable(string dbPath, string tableName) { SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath); if (sqliteConn.State != System.Data.ConnectionState.Open) { sqliteConn.Open(); SQLiteCommand cmd = new SQLiteCommand(); cmd.Connection = sqliteConn; cmd.CommandText = "CREATE TABLE " + tableName + "(Name varchar,Team varchar)"; cmd.ExecuteNonQuery(); } sqliteConn.Close(); } //插入数据 void insert(String sql, String dbPath) { SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath); if (sqliteConn.State != ConnectionState.Open) { sqliteConn.Open(); SQLiteCommand cmd = new SQLiteCommand(); cmd.Connection = sqliteConn; cmd.CommandText = sql; cmd.ExecuteNonQuery(); } sqliteConn.Close(); }//查询全部 static void Select(String sql, String dbPath) { SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath); SQLiteCommand command = new SQLiteCommand(); if (sqliteConn.State != ConnectionState.Open) { sqliteConn.Open(); command.Connection = sqliteConn; command.CommandText = sql; SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) MessageBox.Show("Name: " + reader["Name"] + "\tScore: " + reader["Team"]); } sqliteConn.Close(); } private void button1_Click(object sender, EventArgs e) { CreatDb(); NewTable("test.db", "tablea"); insert("insert into tablea (Name, Team) values ('Myself', 'blue')", "test.db"); } private void button2_Click_1(object sender, EventArgs e) { Select("select * from tablea", "test.db"); } } }