C# SQLite 创建默认数据库 简单示例 笔记

记录笔记:C# 中如何创建SQLite数据库、数据表、插入数据


命名空间:using System.Data.SQLite;

private void CreateDB(string dbPath)
{
	try
	{
		SQLiteConnection.CreateFile(dbPath);
		SQLiteConnection sqliteComm = new SQLiteConnection("data source=" + dbPath);
		if (sqliteComm.State != System.Data.ConnectionState.Open)
		{
			StringBuilder createTable = new StringBuilder();
			createTable.Append("CREATE TABLE ImageListData (imageID INTEGER PRIMARY KEY AUTOINCREMENT, dirID INTEGER, imageName GUID, ImageFullName VARCHAR(48)); ");
			createTable.Append("CREATE TABLE Directory (dirID INTEGER PRIMARY KEY,dirName VARCHAR(30),parentID LARGEINT, level INT);");
			sqliteComm.Open();
			SQLiteCommand cmd = new SQLiteCommand();
			cmd.Connection = sqliteComm;
			cmd.CommandText = createTable.ToString(); 
			cmd.ExecuteNonQuery();

			StringBuilder sql = new StringBuilder();
			sql.Append(string.Format("INSERT INTO  Directory (dirName,parentID,level)" + "  VALUES ({0},{1},{2});", "'FirstLevelCatalog_One'", "-1", "0"));
			// sql.Append(string.Format("INSERT into Directory values (1,'FirstLevelCatalog_One',-1,0);")); 插入语句的第二种方法
			sql.Append(string.Format("INSERT INTO  Directory (dirName,parentID,level)" + "  VALUES ({0},{1},{2});", "'FirstLevelCatalog_Two'", "-1", "0"));
			// sql.Append(string.Format("INSERT into Directory values (2,'FirstLevelCatalog_Two',-1,0);"));
			
			cmd = new SQLiteCommand(sql.ToString(), sqliteComm);
			int rows = cmd.ExecuteNonQuery();
		}
		sqliteComm.Close();
	}
	catch(Exception ex)
	{
	}
}

 

你可能感兴趣的:(C#,数据库,SQLite,数据库创建)