airfling 2019-12-28
操作功能列表:
功能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
以获取表名为例,完整代码为
public DataSet GetTableNames(string path) {
string strSQL = "SELECT name FROM sqlite_master WHERE TYPE=‘table‘ ORDER BY name";
DataSet ds = null;
try {
SQLiteConnection conn = new SQLiteConnection(path);
SQLiteCommand cmd = new SQLiteCommand(strSQL, conn);
SQLiteDataAdapter reciever = new SQLiteDataAdapter(cmd);
ds = new DataSet();
reciever.Fill(ds);
return ds;
} catch {
MessageBox.Show("There is no data table");
}
return ds;
}16 DataSet dbnames = GetTableNames(DBPath);注意此时返回的ds包含的元素数量只有一个,所有表名以列向量的形式存储在一张表中(即ds唯一的元素)。
读取表数量的代码为
int tablecount = dbnames.Tables[0].Rows.Count;
读取索引为X的表名
string tablename = dbnames.Table[0].Rows[X].ItemArray[0].ToString();//X starts from 0
功能2:读取表数据
public DataTable GetDataTable(string strSQL, string path){
DataTable dt = null;
try {
SQLiteConnection conn = new SQLiteConnection(path);
SQLiteCommand cmd = new SQLiteCommand(strSQL,conn);
SQLiteDataAdapter reciever = new SQLiteDataAdapter(cmd);
dt = new DataTable();
reciever.Fill(dt);
return dt;
} catch{
MessageBox.Show("There is no such a datatable");
}
return dt;
}其中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”。