zoukankan      html  css  js  c++  java
  • 【WinForm】杂记(2):C#之操作SQLite数据库(总结)

    操作功能列表:

    • 功能1:读取所有表名/索引/视图
    • 功能2:读取表数据

    功能1:读取所有表名/索引/视图

    每一个 SQLite 数据库都有一个叫sqlit_master的表, 里面存储着数据库的数据结构(表结构、视图结构、索引结构等)。故通过读取sqlit_master便可以获取所有的表格信息。

    获取表名

    SELECT name FROM sqlite_master WHERE TYPE='table' ORDER BY name
    

    获取索引

    SELECT name FROM sqlite_master WHERE TYPE='index' ORDER BY name  

    获取视图

    SELECT name FROM sqlite_master WHERE TYPE='view' ORDER BY name

    以获取表名为例,完整代码为

     1 public DataSet GetTableNames(string path) {
     2     string strSQL = "SELECT name FROM sqlite_master WHERE TYPE='table' ORDER BY name";
     3     DataSet ds = null;
     4     try {
     5         SQLiteConnection conn = new SQLiteConnection(path);
     6         SQLiteCommand cmd = new SQLiteCommand(strSQL, conn);
     7         SQLiteDataAdapter reciever = new SQLiteDataAdapter(cmd);
     8         ds = new DataSet();
     9         reciever.Fill(ds);
    10         return ds;
    11     } catch {
    12         MessageBox.Show("There is no data table");
    13     }
    14     return ds;
    15 }
    16 DataSet dbnames = GetTableNames(DBPath);

    注意此时返回的ds包含的元素数量只有一个,所有表名以列向量的形式存储在一张表中(即ds唯一的元素)。

    读取表数量的代码为

    int tablecount = dbnames.Tables[0].Rows.Count;
    

    读取索引为X的表名

    string tablename = dbnames.Tables[0].Rows[X].ItemArray[0].ToString();//X starts from 0

      

    功能2:读取表数据

     1 public DataTable GetDataTable(string strSQL, string path){
     2     DataTable dt = null;
     3     try {
     4         SQLiteConnection conn = new SQLiteConnection(path);
     5         SQLiteCommand cmd = new SQLiteCommand(strSQL,conn);
     6         SQLiteDataAdapter reciever = new SQLiteDataAdapter(cmd);
     7         dt = new DataTable();
     8         reciever.Fill(dt);
     9         return dt;
    10     } catch{
    11         MessageBox.Show("There is no such a datatable");
    12     }
    13     return dt;
    14 }

      其中strSQL是获取db文件中数据表的指令

    string sSQL = "SELECT * FROM item_compound;";
    

    这里的数据表名为"item_compound"。

    文件路Path

    public static string DBPath = string.Format(@"Data Source={0}", Application.StartupPath + @"CCUS_supstr_temp.db");//the path of .db file 
    

    这里的db文件名为“CCUS_supstr_temp.db”。

  • 相关阅读:
    js + html 实现视频截图
    检测浏览器版本是否支持webp
    【安装系统】win8装win7遇到的一些坑
    《说文解字》与程序设计
    朝花夕拾——更新两个开源项目
    js发送和接收二进制字节流数据
    字符编码--丛起原到代码
    JavaScript进行WebSocket字节流通讯示例
    JavaScript进行UTF-8编码与解码
    JS字符串与二进制的相互转化
  • 原文地址:https://www.cnblogs.com/RicardoIsLearning/p/12103814.html
Copyright © 2011-2022 走看看