当前位置:网站首页>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 .
边栏推荐
- Chapter IX app project test (the end of this chapter)
- File常用工具类, 流相关运用 (记录)
- I am 35 years old. Can I change my career to be a programmer?
- Wechat official account - menu
- 信息学奥赛一本通2062:电影票
- Unity C# 基础复习27——委托示例(P448)
- Lumiprobe reactive dye carboxylic acid: sulfo cyanine7.5 carboxylic acid
- Render follows, encapsulating a form and adding data to the table
- Lumiprobe reactive dye miscellaneous dye: BDP FL ceramide
- MCS:离散随机变量——几何分布
猜你喜欢
随机推荐
深入理解 Promise 之手把手教你写一版
信息学奥赛一本通2061:梯形面积
高分三号卫星(GF-3)简介
分页sql(rownum、row_number、dense_rank、rank)
复数卷积神经网络:CV-CNN
Unity C# 基础复习27——委托示例(P448)
ROS 笔记(10)— launch 文件启动
Is it safe to open a stock account at present? Can I open an account online directly
雷达发射机
揭秘百度智能测试在测试自动执行领域实践
Ink drop typesetting
Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear
Is it reliable to invest in REITs funds? Is REITs funds safe
动态监听DOM元素高度变化
MySQL为什么选择B+树存储索引
What is the relationship between synchronized and multithreading
c#Sqlite类库
curl: (56) Recv failure: Connection reset by peer
ImgUtil 图片处理工具类,文字提取,图片水印
MCS:离散随机变量——Pascal分布







