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; } }
獲取表字段的操作代碼如下所示。
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; }
為了實現和我代碼生成工具中的數據庫字段信息綁定,需要通過獲取設置Sqlite的屬性為對應的ColumnInfo對象,如下所示。
using (SQLiteConnection conn = new SQLiteConnection(ConnectString)) { conn.Open(); DataTable schemaTable = GetReaderSchema(tableName, conn); foreach (DataRow dr in schemaTable.Rows) { ColumnInfo info = new ColumnInfo(); info.Name = new NameElement(dr["ColumnName"].ToString()); info.Ordinal = Convert.ToInt32(dr["ColumnOrdinal"].ToString()); info.AllowDBNull = (bool)dr["AllowDBNull"]; info.MaxLength = Convert.ToInt32(dr["ColumnSize"].ToString()); info.DataTypeId = Convert.ToInt32(dr["ProviderType"].ToString()); info.DataType = dr["DataTypeName"].ToString().Trim(); info.AutoIncrement = (bool)dr["IsAutoIncrement"]; info.IsPrimaryKey = (bool)dr["IsKey"]; info.Unique = (bool)dr["IsUnique"]; info.IsReadOnly = (bool)dr["IsReadOnly"]; string netType = dr["DataType"].ToString(); list.Add(info.Name.Name.ToString(), info); } conn.Close(); }
代碼生成工具中,這些數據庫的元數據實體類信息是可以提供訪問的,方便我們定制代碼生成工具的模板,代碼生成工具關於這些數據庫對象的幫助如下所示。
這樣,在代碼生成工具中,就可以利用Sqlite的數據庫對象數據,來生成和Oracle數據庫、SqlServer數據庫、Access數據庫、MySql等數據庫一樣的項目工程代碼了,獲取甚至可以在自定義的模板代碼模塊中,添加自己的處理邏輯。
快速生成的代碼如下所示。
本文通過介紹獲取Sqlite的數據庫元數據庫,並在代碼生成工具中的應用為例,給大家提供一個使用元數據進行程序開發的一個思路,希望大家可以同這種方式實現更多自定義模板或者邏輯的引用。
天下雖大同,一直在努力,孜孜不倦,終有所獲。