【IT168 技术】SQLite数据库,在很多场合已经用得比较多,由于我的代码生成工具的需要,需要把SQLite的表、字段、视图等信息获取出来,以便实现各种数据库快速生成项目工程的操作。这里就需要利用C#获取SQLite数据库的元数据了,和其他数据库一样。
为了获取SQLite的数据库对象数据,我做了一个测试的例子来获取他的相关信息,其实它的元数据还是和Access的操作方式很接近。首先我们先通过SQLite的数据库管理工具或者Visual Studio来打开创建一些表,如下所示。
首先我们先来看看通过C#代码获取到数据库对象的操作界面,如下所示。
获取表的元数据界面效果如下所示,视图和这个也查不多,很有意思的一点,就是它把创建的脚本的显示出来了。
获取的表字段信息效果如下所示。
有了这些数据,我就很方便在我的代码生成工具Database2Sharp里面实现代码生成操作了。
现在我们来看看以上实现的后台代码是如何的,来了解SQLite的数据库获取元数据的操作。
string connectionString = "";
public Form1()
{
InitializeComponent();
connectionString = string.Format(@"Data Source={0}\OrderWater.db;Version=3;", Application.StartupPath);
}
private void btnGetSchema_Click(object sender, EventArgs e)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
DataTable schemaTable = conn.GetSchema("TABLES");
this.dataGridView1.DataSource = schemaTable;
}
}
public Form1()
{
InitializeComponent();
connectionString = string.Format(@"Data Source={0}\OrderWater.db;Version=3;", Application.StartupPath);
}
private void btnGetSchema_Click(object sender, EventArgs e)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
DataTable schemaTable = conn.GetSchema("TABLES");
this.dataGridView1.DataSource = schemaTable;
}
}
获取表字段的操作代码如下所示。
private void btnGetColumns_Click(object sender, EventArgs e)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
DataTable table = conn.GetSchema("TABLES");
if (table != null && table.Rows.Count > 0)
{
string tableName = table.Rows[0]["TABLE_NAME"].ToString();
DataTable schemaTable = GetReaderSchema(tableName, conn);
this.dataGridView1.DataSource = schemaTable;
}
}
}
private DataTable GetReaderSchema(string tableName, SQLiteConnection connection)
{
DataTable schemaTable = null;
IDbCommand cmd = new SQLiteCommand();
cmd.CommandText = string.Format("select * from [{0}]", tableName);
cmd.Connection = connection;
using (IDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly))
{
schemaTable = reader.GetSchemaTable();
}
return schemaTable;
}
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
DataTable table = conn.GetSchema("TABLES");
if (table != null && table.Rows.Count > 0)
{
string tableName = table.Rows[0]["TABLE_NAME"].ToString();
DataTable schemaTable = GetReaderSchema(tableName, conn);
this.dataGridView1.DataSource = schemaTable;
}
}
}
private DataTable GetReaderSchema(string tableName, SQLiteConnection connection)
{
DataTable schemaTable = null;
IDbCommand cmd = new SQLiteCommand();
cmd.CommandText = string.Format("select * from [{0}]", tableName);
cmd.Connection = connection;
using (IDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly))
{
schemaTable = reader.GetSchemaTable();
}
return schemaTable;
}