我想获取 Sqlite3 数据库中每个表的行数。我想避免写出手写查询。我可以得到这样的表列表:
SELECT name FROM sqlite_master WHERE type='table'
我想在这样的子查询中使用它:
select count (*) from (SELECT name FROM sqlite_master WHERE type='table');
但只会返回子查询中的总行数,这不是我想要的。
如何编写一个查询来列出每个表及其计数?
我见过 dynamic SQL 这种东西,但我认为 SQLite 没有。
我已经编写了一个 bash 循环来执行此操作,但我更愿意将其作为单个查询来完成
for t in $(sqlite3 data.db "SELECT name FROM sqlite_master WHERE type='table'"); do
echo -n "$t = "; sqlite3 data.db "SELECT COUNT(*) FROM $t;"
done
想法赞赏
我使用以下 shell 语法盲目地从我正在调试的数据库中的表中获取计数。
db="database.db"
for i in `sqlite3 "$db" "SELECT name FROM sqlite_master WHERE
type='table';"`; do echo -n $i\ \=\ ; sqlite3 "$db" "SELECT
COUNT(*) FROM $i;"; done
cols = 0
sqlite_sequence = 0
datacols = 17
hits = 0
host = 0
document = 0
admin = 2
comments = 0
如果您想了解这些值以进行调试,请查看 sqlite3_analyzer 工具的输出。
如果您想在程序中使用这些值,则必须在程序中动态生成查询。
我希望下面的代码能够完整地用于某些人。
我用C#.net编程语言编写了示例代码,Nuget包是Microsoft.Data.Sqlite,版本为7.0.10
代码:
internal class Program
{
static void Main(string[] args)
{
string dbMainQuery = $" WITH x(i) AS (select name from \"main\".sqlite_master WHERE type='table') \r\n SELECT PRINTF('SELECT count(*) as NumberOfRow FROM %s;',i) as QueryInfo,i as Tablename FROM x ;";
DataTable dtMain = new DataTable();
DataTable dtTableCountInfo = new DataTable();
dtTableCountInfo.Columns.Add("Id", typeof(string));
dtTableCountInfo.Columns.Add("TableName", typeof(string));
dtTableCountInfo.Columns.Add("TotalCount", typeof(string));
//Get the sqlite all db data
using (SqliteConnection sqliteConnection = new SqliteConnection("Data Source=dataStoreage.db;Pooling=True;"))
{
sqliteConnection.Open();
using var transaction = sqliteConnection.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
using SqliteCommand sqliteCommand = new SqliteCommand(dbMainQuery, sqliteConnection, transaction);
var dataReader = sqliteCommand.ExecuteReader(CommandBehavior.Default);
dtMain.Load(dataReader);
// Itration on the each table and get the row numbers
if (dtMain.Rows.Count > 0)
{
for (int i = 0; i < dtMain.Rows.Count; i++)
{
var rowInfo = dtTableCountInfo.NewRow();
using SqliteCommand countInfoCmd = new SqliteCommand(dtMain.Rows[i][0].ToString(), sqliteConnection, transaction);
rowInfo["Id"] = i + 1;
rowInfo["TableName"] = dtMain.Rows[i][1].ToString();
rowInfo["TotalCount"] = countInfoCmd.ExecuteScalar();
dtTableCountInfo.Rows.Add(rowInfo);
}
}
transaction.Commit();
// TO DO : do the conversion of the data table as per your needs
}
catch (Exception e)
{
transaction.RollbackAsync();
}
}
Console.ReadLine();
}
}
和模型类:
public class TableSummryReport
{
public string Id { get; set; }
public string TableName { get; set; }
public string TotalCount { get; set; }
}