当前位置:网站首页>C SQLite class library
C SQLite class library
2022-06-29 15:23:00 【Game programming】
String rotation Datetime Mining pit
1. Note the date format saved to the database DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
If the format is not uniform, the search will be inaccurate .
2. Table design recommendations sqlitestudio Tools
using System;using System.Collections.Generic;using System.Text;namespace System.Data.SQLite{ public class SQLiteColumn { public string ColumnName = ""; public bool PrimaryKey = false; public ColType ColDataType = ColType.Text; public bool AutoIncrement = false; public bool NotNull = false; public string DefaultValue = ""; public SQLiteColumn() { } public SQLiteColumn(string colName) { ColumnName = colName; PrimaryKey = false; ColDataType = ColType.Text; AutoIncrement = false; } public SQLiteColumn(string colName, ColType colDataType) { ColumnName = colName; PrimaryKey = false; ColDataType = colDataType; AutoIncrement = false; } public SQLiteColumn(string colName, bool autoIncrement) { ColumnName = colName; if (autoIncrement) { PrimaryKey = true; ColDataType = ColType.Integer; AutoIncrement = true; } else { PrimaryKey = false; ColDataType = ColType.Text; AutoIncrement = false; } } public SQLiteColumn(string colName, ColType colDataType, bool primaryKey, bool autoIncrement, bool notNull, string defaultValue) { ColumnName = colName; if (autoIncrement) { PrimaryKey = true; ColDataType = ColType.Integer; AutoIncrement = true; } else { PrimaryKey = primaryKey; ColDataType = colDataType; AutoIncrement = false; NotNull = notNull; DefaultValue = defaultValue; } } }}using System;using System.Collections.Generic;using System.Text;namespace System.Data.SQLite{ public class SQLiteColumnList : IList<SQLiteColumn> { List<SQLiteColumn> _lst = new List<SQLiteColumn>(); private void CheckColumnName(string colName) { for (int i = 0; i < _lst.Count; i++) { if (_lst[i].ColumnName == colName) throw new Exception("Column name of \"" + colName + "\" is already existed."); } } public int IndexOf(SQLiteColumn item) { return _lst.IndexOf(item); } public void Insert(int index, SQLiteColumn item) { CheckColumnName(item.ColumnName); _lst.Insert(index, item); } public void RemoveAt(int index) { _lst.RemoveAt(index); } public SQLiteColumn this[int index] { get { return _lst[index]; } set { if (_lst[index].ColumnName != value.ColumnName) { CheckColumnName(value.ColumnName); } _lst[index] = value; } } public void Add(SQLiteColumn item) { CheckColumnName(item.ColumnName); _lst.Add(item); } public void Clear() { _lst.Clear(); } public bool Contains(SQLiteColumn item) { return _lst.Contains(item); } public void CopyTo(SQLiteColumn[] array, int arrayIndex) { _lst.CopyTo(array, arrayIndex); } public int Count { get { return _lst.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(SQLiteColumn item) { return _lst.Remove(item); } public IEnumerator<SQLiteColumn> GetEnumerator() { return _lst.GetEnumerator(); } Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return _lst.GetEnumerator(); } }}using System;using System.Collections.Generic;using System.Text;namespace System.Data.SQLite{ public class SQLiteTable { public string TableName = ""; public SQLiteColumnList Columns = new SQLiteColumnList(); public SQLiteTable() { } public SQLiteTable(string name) { TableName = name; } }}using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Globalization;using System.IO;namespace System.Data.SQLite{ public enum ColType { Text, DateTime, Integer, Decimal, BLOB } public class SQLiteHelper { public static string ConnectionString = " route "; public string Error = ""; /// <summary> /// Create database /// </summary> public bool CreateDataBase() { string path = Path.GetDirectoryName(ConnectionString.Replace("data source=", "")); if ((!string.IsNullOrWhiteSpace(path)) && (!Directory.Exists(path))) { Directory.CreateDirectory(path); } if (!File.Exists(ConnectionString)) { SQLiteConnection.CreateFile(ConnectionString); } return true; } // Create table code : //SQLiteTable tb = new SQLiteTable("person"); //tb.Columns.Add(new SQLiteColumn("id", true)); //tb.Columns.Add(new SQLiteColumn("name")); //tb.Columns.Add(new SQLiteColumn("membershipid", ColType.Integer)); //tb.Columns.Add(new SQLiteColumn("level", ColType.Decimal, false, false, "5.5")); //sh.CreateTable(tb); /// <summary> /// Create table /// </summary> /// <param name="table"></param> /// <returns></returns> public bool CreateTable(SQLiteTable table) { StringBuilder sb = new Text.StringBuilder(); sb.Append("create table if not exists `"); sb.Append(table.TableName); sb.AppendLine("`("); bool firstRecord = true; foreach (SQLiteColumn col in table.Columns) { if (col.ColumnName.Trim().Length == 0) { throw new Exception("Column name cannot be blank."); } if (firstRecord) firstRecord = false; else sb.AppendLine(","); sb.Append(col.ColumnName); sb.Append(" "); if (col.AutoIncrement) { sb.Append("integer primary key autoincrement"); continue; } switch (col.ColDataType) { case ColType.Text: sb.Append("text"); break; case ColType.Integer: sb.Append("integer"); break; case ColType.Decimal: sb.Append("decimal"); break; case ColType.DateTime: sb.Append("datetime"); break; case ColType.BLOB: sb.Append("blob"); break; } if (col.PrimaryKey) sb.Append(" primary key"); else if (col.NotNull) sb.Append(" not null"); else if (col.DefaultValue.Length > 0) { sb.Append(" default "); if (col.DefaultValue.Contains(" ") || col.ColDataType == ColType.Text || col.ColDataType == ColType.DateTime) { sb.Append("'"); sb.Append(col.DefaultValue); sb.Append("'"); } else { sb.Append(col.DefaultValue); } } } sb.AppendLine(");"); try { using (SQLiteConnection conn = new SQLiteConnection(ConnectionString)) { conn.Open(); SQLiteCommand comm = new SQLiteCommand(); comm.Connection = conn; comm.CommandText = sb.ToString(); comm.CommandType = CommandType.Text; comm.CommandTimeout = conn.ConnectionTimeout; comm.ExecuteNonQuery(); conn.Close(); } return true; } catch (Exception ex) { Error = " System failure :GetDataSetBySQLString," + ex.ToString(); return false; } } /// <summary> /// Query data /// </summary> public DataTable GetDataTableBySql(string sql) { return GetDataSetBySQLString(sql).Tables[0]; } public DataSet GetDataSetBySQLString(string SQLString) { try { using (SQLiteConnection conn = new SQLiteConnection(ConnectionString)) { conn.Open(); SQLiteCommand comm = new SQLiteCommand(); comm.Connection = conn; comm.CommandText = SQLString; comm.CommandType = CommandType.Text; comm.CommandTimeout = conn.ConnectionTimeout; DataSet ds = new DataSet("SQLDataSet"); SQLiteDataAdapter adapter = new SQLiteDataAdapter(); adapter.SelectCommand = comm; adapter.Fill(ds, "SQLDataSet"); conn.Close(); return ds; } } catch (Exception ex) { Error = " System failure :GetDataSetBySQLString," + ex.ToString(); return null; } } /// <summary> /// Add or update data /// </summary> public int UpdateBySQL(string sql) { using (SQLiteConnection con = new SQLiteConnection(ConnectionString)) { con.Open(); SQLiteCommand cmd = null; try { cmd = new SQLiteCommand(sql, con); object objResult = cmd.ExecuteScalar(); con.Close(); if (objResult == null) { return 0; } else { return 1; } } catch (Exception ex) { Error = ex.ToString(); con.Close(); Error = " System failure :UpdateBySQL," + ex.ToString(); return -1; } } } /// <summary> /// Delete database data /// </summary> public int DeltetBySQL(string sql) { using (SQLiteConnection con = new SQLiteConnection(ConnectionString)) { con.Open(); SQLiteCommand cmd = null; try { cmd = new SQLiteCommand(sql, con); int objResult = cmd.ExecuteNonQuery(); con.Close(); return 0; } catch (Exception ex) { Error = ex.ToString(); con.Close(); Error = " System failure :DeltetBySQL," + ex.ToString(); return -1; } } } }} Calling method
SQLiteHelper.ConnectionString ="data source=F:\db\Db_Phone";
// Create database
SQLiteHelper sh = new SQLiteHelper();
// Create table
SQLiteTable tb = new SQLiteTable("person");
tb.Columns.Add(new SQLiteColumn("id", true));
tb.Columns.Add(new SQLiteColumn("name"));
tb.Columns.Add(new SQLiteColumn("membershipid", ColType.Integer));
tb.Columns.Add(new SQLiteColumn("level", ColType.Decimal, false, false, "5.5"));
sh.CreateTable(tb);
// Call statement
string sql = string.Format("INSERT INTO PicFiles (SN,Path,Createdate) VALUES ('{0}','{1}','{2}')", "fan", "wen", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
int rel = sh.UpdateBySQL(sql);
author :fanwenhu
Game programming , A game development favorite ~
If the picture is not displayed for a long time , Please use Chrome Kernel browser .
边栏推荐
- Northwestern Polytechnic University attacked by overseas e-mail
- 请说下redis命令的时间复杂度??(实际问的是redis底层结构)
- 雷达相关内容简介
- MySQL JSON array operation JSON_ array_ append、json_ array_ insert
- 真正的软件测试人员 =“半个产品+半个开发”?
- Flink SQL任务TaskManager内存设置
- What is the relationship between synchronized and multithreading
- 雷达天线简介
- Lumiprobe click chemistry - non fluorescent azide: azide-peg3-oh
- Const usage
猜你喜欢

信息学奥赛一本通1194:移动路线

Lumiprobe 脱氧核糖核酸丨磷酸盐 CPG 1000 固体载体

第九章 APP项目测试(此章完结)

Lumiprobe deoxyribonucleic acid alkyne DT phosphimide

Lumiprobe reactive dye - amino dye: cyanine 5 amine

MCS:多元随机变量——多项式分布

ImgUtil 图片处理工具类,文字提取,图片水印

Uncover the practice of Baidu intelligent test in the field of automatic test execution

Pytorch two-dimensional multi-channel convolution operation method

阿尔兹海默病智能诊断
随机推荐
File常用工具類, 流相關運用 (記錄)
SSL V**技术原理
使用自定义注解实现Redis分布式锁
目前股票开户安全吗?可以直接网上开户吗
数据挖掘复习
Lumiprobe 点击化学丨非荧光炔烃:己酸STP酯
Unity C basic review 27 - delegation example (p448)
MCS: discrete random variable - Hyper geometric distribution
真正的软件测试人员 =“半个产品+半个开发”?
What is the relationship between synchronized and multithreading
swift JSONSerialization
Chapter IX app project test (4) test tools
信息学奥赛一本通1001:Hello,World!
ROS 笔记(10)— launch 文件启动
极化SAR几种成像模式
Lumiprobe reactive dye miscellaneous dye: BDP FL ceramide
Lumiprobe reactive dye carboxylic acid: sulfo cyanine7.5 carboxylic acid
在shop工程中,实现一个菜单(增删改查)
bash汇总线上日志
PostgreSQL learning (based on rookie course)