本文整理汇总了C#中System.Data.SQLite.SQLiteConnection.GetSchema方法的典型用法代码示例。如果您正苦于以下问题:C# SQLiteConnection.GetSchema方法的具体用法?C# SQLiteConnection.GetSchema怎么用?C# SQLiteConnection.GetSchema使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Data.SQLite.SQLiteConnection
的用法示例。
在下文中一共展示了SQLiteConnection.GetSchema方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DBViewModel
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public DBViewModel(string dbName, string dbPath)
{
this.dbName = dbName;
this.dbPath = dbPath;
try
{
SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
builder.DataSource = DBPath;
conn = new SQLiteConnection(builder.ConnectionString);
conn.Open();
var schema = conn.GetSchema("Tables");
foreach (System.Data.DataRow row in schema.Rows)
{
try
{
TableViewModel table = new TableViewModel(row.ItemArray[2].ToString(), row.ItemArray[6].ToString(), conn);
Tables.Add(table);
}
catch(Exception)
{
continue;
}
}
IsValid = true;
}
catch (Exception ex)
{
IsValid = false;
System.Windows.MessageBox.Show(ex.Message);
}
}
示例2: Create_JoinDatabase
private void Create_JoinDatabase()
{
if (!System.IO.File.Exists("MyDatabase.sqlite"))
{
SQLiteConnection.CreateFile("MyDatabase.sqlite");
}
m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
bool exists = false;
DataTable dt = m_dbConnection.GetSchema("Tables");
foreach (DataRow row in dt.Rows)
{
string tablename = (string)row[2];
if (tablename == "MailList") exists = true;
}
if (!exists)
{
string sql = "CREATE TABLE MailList(MessageId varchar(50) not null, Receiver varchar(50), Sender varchar(50), Date varchar(20), Subject varchar(60), Container varchar(20), UNIQUE(MessageId))";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
//sql = "insert into highscores (name, score) values ('Me', 9001)";
//command = new SQLiteCommand(sql, m_dbConnection);
//command.ExecuteNonQuery();
m_dbConnection.Close();
}
示例3: CreateDatabase
public static void CreateDatabase()
{
#region create non existing database
if (!System.IO.File.Exists("MyDatabase.sqlite"))
{
SQLiteConnection.CreateFile("MyDatabase.sqlite");
}
#endregion
// open connection
dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
dbConnection.Open();
#region create non existing table
bool exists = false;
DataTable dt = dbConnection.GetSchema("Tables");
foreach (DataRow row in dt.Rows)
{
string tablename = (string)row[2];
if (tablename == "MailList") exists = true;
}
if (!exists)
{
string sql = "CREATE TABLE MailList(MessageId varchar(50) not null, Receiver varchar(50), Sender varchar(50), Date varchar(20), Subject varchar(60), Message blob, UNIQUE(MessageId))";
SQLiteCommand command = new SQLiteCommand(sql, dbConnection);
command.ExecuteNonQuery();
}
#endregion
dbConnection.Close();
}
示例4: Main
static void Main(string[] args)
{
string fn =
"Northwind.sqlite";
//Path.Combine(
// Path.GetDirectoryName(
// typeof(Program).Assembly.CodeBase),
// "Northwind.sqlite");
using (SQLiteConnection con =
new SQLiteConnection("data source=" + fn))
{
con.Open();
// ExecuteReader Örneği
//SQLiteCommand com = new SQLiteCommand(
// "SELECT * FROM Products;",
// con);
//SQLiteDataReader dr = com.ExecuteReader();
//while (dr.Read())
//{
// Console.WriteLine("{0,5} {1,-20} {2:C} {3}",
// dr.GetInt32(0),
// dr.GetString(dr.GetOrdinal("ProductName")),
// dr.GetDouble(dr.GetOrdinal("UnitPrice")),
// dr.GetInt32(dr.GetOrdinal("UnitsInStock"))
// );
//}
//// Execute Non Query Örneği
//SQLiteCommand com = new SQLiteCommand();
//com.CommandText =
// "INSERT INTO Products"+
// "(ProductName, CategoryID, UnitPrice, UnitsInStock) "+
// "VALUES('Kağıt', 1, 0.10, 1000);";
//com.Connection = con;
//com.ExecuteNonQuery();
DataTable dt = con.GetSchema("Tables");
}
}
示例5: connectDB
private void connectDB()
{
sql_con = new SQLiteConnection("Data Source=" + sDataFileFull + ";Version=3;New=False;Compress=True;Synchronous=Off");
sql_con.Open();
try
{
DataTable dtTest = sql_con.GetSchema("Tables", new string[] { null, null, "VMUsage", null });
}
catch (SQLiteException ex)
{
System.Diagnostics.Debug.WriteLine("SQLiteException in connectDB(): " + ex.Message);
}
catch (DataException ex)
{
System.Diagnostics.Debug.WriteLine("DataException in connectDB(): " + ex.Message);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception in connectDB(): " + ex.Message);
}
sql_cmd.Connection = sql_con;
}
示例6: TableExists
protected bool TableExists(string table)
{
using (var conn = new SQLiteConnection(dbConnection))
{
conn.Open();
var data = conn.GetSchema("Tables").Select(String.Format("Table_name = '{0}'", table));
return (data.Length > 0);
}
}
示例7: GetMessagesInfoSqlCon
/// <summary>
/// Gets messages info sql connection.
/// </summary>
/// <param name="user">User name.</param>
/// <param name="folder">User-relative folder name with optional path.</param>
/// <returns>Returns messages info sql connection.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>user</b> or <b>folder</b> is null reference.</exception>
/// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
private SQLiteConnection GetMessagesInfoSqlCon(string user,string folder)
{
if(user == null){
throw new ArgumentNullException("user");
}
if(user == string.Empty){
throw new ArgumentException("Argument 'user' value must be specified.","user");
}
if(folder == null){
throw new ArgumentNullException("folder");
}
if(folder == string.Empty){
throw new ArgumentException("Argument 'folder' value must be specified.","folder");
}
string path = m_MailStorePath + "Mailboxes\\" + user + "\\" + IMAP_Utils.Encode_IMAP_UTF7_String(folder);
SQLiteConnection con = new SQLiteConnection("Data Source=\"" + path + "\\_MessagesInfo.db3\";Pooling=false");
con.Open();
// Messages info already exists.
if(con.GetSchema("Tables").Select("Table_Name = 'MessagesInfo'").Length > 0){
return con;
}
SQLiteCommand cmd = con.CreateCommand();
// Begin exclusive transaction, so other threads can't read/write data to messages info database while we create it.
cmd.CommandText = "BEGIN EXCLUSIVE TRANSACTION;";
cmd.ExecuteNonQuery();
try{
cmd.CommandText = "create table MessagesInfo(ID,UID INTEGER,Size INTEGER,Flags,InternalDateTime INTEGER,InternalDate INTEGER,Header,HeaderDecoded,Structure,StructureDecoded,Header_Bcc,Header_Cc,Header_From,Header_Date INTEGER,Header_Subject,Header_To,TextParts);";
cmd.ExecuteNonQuery();
#region Convert 0.93 to latest
#pragma warning disable
// Try to build message flags index from old version data.
// REMOVE ME: In future.
Dictionary<long,string[]> uidToFlags = new Dictionary<long,string[]>();
try{
if(File.Exists(path + "\\_flags.txt")){
using(FileStream fs = File.Open(path + "\\_flags.txt",FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite)){
TextReader r = new StreamReader(fs);
string line = r.ReadLine();
while(line != null){
// Skip comment lines and deleted rows
if(!(line.StartsWith("#") || line.StartsWith("\0"))){
string[] userID_uid_flags = line.Split(' ');
if(uidToFlags.ContainsKey(Convert.ToInt32(userID_uid_flags[1]))){
// This should never happen. TODO: ?
}
else{
List<string> flags = new List<string>();
IMAP_MessageFlags f = (IMAP_MessageFlags)Convert.ToInt32(userID_uid_flags[2]);
if((f & IMAP_MessageFlags.Answered) != 0){
flags.Add("Answered");
}
if((f & IMAP_MessageFlags.Deleted) != 0){
flags.Add("Deleted");
}
if((f & IMAP_MessageFlags.Draft) != 0){
flags.Add("Draft");
}
if((f & IMAP_MessageFlags.Flagged) != 0){
flags.Add("Flagged");
}
if((f & IMAP_MessageFlags.Recent) != 0){
flags.Add("Recent");
}
if((f & IMAP_MessageFlags.Seen) != 0){
flags.Add("Seen");
}
uidToFlags.Add(Convert.ToInt32(userID_uid_flags[1]),flags.ToArray());
}
}
line = r.ReadLine();
}
}
}
}
catch{
}
#pragma warning enable
#endregion
//.........这里部分代码省略.........
示例8: DataTable
DataTable IPlugin.GetForeignKeys(string database, string table)
{
DataTable metaData = new DataTable();
try
{
using (SQLiteConnection cn = new SQLiteConnection(this.context.ConnectionString))
{
cn.Open();
DataTable dt = cn.GetSchema("ForeignKeys", new string[] { database, null, null }); //table });
cn.Close();
metaData = context.CreateForeignKeysDataTable();
foreach (DataRow dtRow in dt.Rows)
{
string pkTable = (string)dtRow["TABLE_NAME"];
string fkTable = (string)dtRow["FKEY_TO_TABLE"];
if (pkTable != table && fkTable != table) continue;
DataRow row = metaData.NewRow();
metaData.Rows.Add(row);
DumpRow(dtRow);
row["FK_NAME"] = dtRow["CONSTRAINT_NAME"];
row["PK_TABLE_CATALOG"] = dtRow["FKEY_TO_CATALOG"];
row["PK_TABLE_SCHEMA"] = dtRow["FKEY_TO_SCHEMA"];
row["PK_TABLE_NAME"] = dtRow["FKEY_TO_TABLE"];
row["FK_TABLE_CATALOG"] = dtRow["TABLE_CATALOG"];
row["FK_TABLE_SCHEMA"] = dtRow["TABLE_SCHEMA"];
row["FK_TABLE_NAME"] = dtRow["TABLE_NAME"];
row["FK_COLUMN_NAME"] = dtRow["FKEY_FROM_COLUMN"];
row["PK_COLUMN_NAME"] = dtRow["FKEY_TO_COLUMN"];
cn.Open();
DataTable colMetadata = cn.GetSchema("Columns", new string[] { database, null, (string)dtRow["TABLE_NAME"] });
cn.Close();
for (int i = 0; i < colMetadata.Rows.Count; i++)
{
DataRow colRow = colMetadata.Rows[i];
if (colRow["PRIMARY_KEY"] != DBNull.Value)
{
bool pk = (bool)colRow["PRIMARY_KEY"];
if (pk)
{
row["PK_NAME"] = colRow["COLUMN_NAME"];
}
}
}
}
}
}
catch { }
return metaData;
}
示例9: isVersionComp
// =====================================================================================
// Vérification si la table est bien compatible
public bool isVersionComp(String version)
{
try
{
using (SQLiteConnection SQLC = new SQLiteConnection(this._connectionString))
{
if (File.Exists(this.path))
SQLC.Open();
else
throw new Exception("Base inaccessible");
if (SQLC.GetSchema("Tables").Select("Table_Name = 'Properties'").Length > 0) // Version >= 0.7
using (SQLiteCommand SQLCmd = new SQLiteCommand(SQLC))
{
// Création d'une nouvelle commande à partir de la connexion
SQLCmd.CommandText = "SELECT rowid FROM Properties WHERE Cle='ActionsDBVer' AND Valeur='" + version + "';";
using (SQLiteDataReader SQLDReader = SQLCmd.ExecuteReader())
{
ArrayList liste = new ArrayList();
// La méthode Read() lit l'entrée actuelle puis renvoie true tant qu'il y a des entrées à lire.
while (SQLDReader.Read())
liste.Add(SQLDReader[0]); // On retourne la seule et unique colonne
return (liste.Count > 0);
}
}
else
return false;
}
}
catch (SQLiteException Ex)
{
// On affiche l'erreur.
MessageBox.Show(Ex.Message + Environment.NewLine + Ex.StackTrace,
"Exception sur isVersionComp",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return false;
}
}
示例10: Main
static void Main(string[] args)
{
string dbLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tilecache.s3db");
int minz = 7;
int maxz = 10;
double minx = -95.844727;
double miny = 35.978006;
double maxx = -88.989258;
double maxy = 40.563895;
string mapServiceUrl = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer";
int maxDegreeOfParallelism = 10;
bool replaceExistingCacheDB = true;
bool showHelp = false;
bool verbose = false;
string mapServiceType = "agsd";
string settings = string.Empty;
bool showInfo = false;
ITileUrlSource tileSource = new OSMTileUrlSource()
{
MapServiceUrl = TileHelper.OSM_BASE_URL_TEMPLATE,
};
var options = new OptionSet()
{
{"h|?|help", "Show this message and exits", h => showHelp = h != null},
{"v|verbose", "Display verbose information logs while running", v => verbose = v != null},
{"t|type=", "Type of the map service to be cached", t => mapServiceType = t.ToLower()},
{"m|mapservice=", "Url of the Map Service to be cached", m => mapServiceUrl = m},
{"s|settings=", "Extra settings needed by the type of map service being used", s => settings = s},
{"o|output=", "Complete file path and file name where the tile cache needs to be outputted", o => dbLocation = o},
{"z|minz=", "Minimum zoom scale at which to begin caching", z => int.TryParse(z, out minz)},
{"Z|maxz=", "Maximum zoom scale at which to end caching", Z => int.TryParse(Z, out maxz)},
{"x|minx=", "Minimum X coordinate value of the extent to cache", x => double.TryParse(x, out minx)},
{"y|miny=", "Minimum Y coordinate value of the extent to cache", y => double.TryParse(y, out miny)},
{"X|maxx=", "Maximum X coordinate value of the extent to cache", X => double.TryParse(X, out maxx)},
{"Y|maxy=", "Maximum Y coordinate value of the extent to cache", Y => double.TryParse(Y, out maxy)},
{"p|parallelops=", "Limits the number of concurrent operations run by TileCutter", p => int.TryParse(p, out maxDegreeOfParallelism)},
{"r|replace=", "Delete existing tile cache MBTiles database if already present and create a new one.", r => Boolean.TryParse(r, out replaceExistingCacheDB)},
{"i|info=", "", i => showInfo = i != null}
};
options.Parse(args);
if (showHelp)
{
ShowHelp(options);
return;
}
var tiles = GetTiles(minz, maxz, minx, miny, maxx, maxy);
if (showInfo)
{
var zoomLevels = Enumerable.Range(0, 21);
var tileCountByZoomLevel = new Dictionary<int, int>();
foreach (var level in zoomLevels)
tileCountByZoomLevel[level] = 0;
foreach (var tile in tiles)
tileCountByZoomLevel[tile.Level]++;
foreach (var item in tileCountByZoomLevel)
if (item.Value > 0)
Console.WriteLine(string.Format("Zoom level {0} - {1} tiles", item.Key, item.Value));
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
return;
}
if (!string.IsNullOrEmpty(mapServiceType))
tileSource = GetTileSource(mapServiceType, mapServiceUrl, settings);
string tileCacheDirectory = Path.GetDirectoryName(dbLocation);
string tilecacheFileName = Path.GetFileNameWithoutExtension(dbLocation);
if (!Directory.Exists(tileCacheDirectory))
{
Console.WriteLine("The tilecache path provided is not valid");
return;
}
string errorLogFile = Path.Combine(tileCacheDirectory, tilecacheFileName + ".log");
//if the user option to delete existing tile cache db is true delete it or else add to it
if (replaceExistingCacheDB && File.Exists(dbLocation))
File.Delete(dbLocation);
//Connect to the sqlite database
string connectionString = string.Format("Data Source={0}; FailIfMissing=False", dbLocation);
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
//Check if the 'metadata' table exists, if not create it
var rows = connection.GetSchema("Tables").Select("Table_Name = 'metadata'");
if (!rows.Any())
{
var command = connection.CreateCommand();
command.CommandText = "CREATE TABLE metadata (name text, value text);";
command.ExecuteNonQuery();
connection.Execute("CREATE UNIQUE INDEX name ON metadata ('name')");
connection.Execute(@"INSERT INTO metadata(name, value) values (@a, @b)",
new[] {
new { a = "name", b = "cache" },
//.........这里部分代码省略.........
示例11: PostProcess
private void PostProcess(object sender, EventArgs e)
{
const string transferFormat = "INSERT INTO main.{0} ({1} ) SELECT {1} from tmp{0}.{0}_tmp;";
BulkCopyTask task = (BulkCopyTask) sender;
if (task.State != CopyEventType.Processing)
{
// dont want to merge suspect results
return;
}
task.OnRowsInserted(CopyEventType.Processing, "Waiting to merge...");
string table = task.Table;
string sourcePath = Path.Combine(_targetPath, string.Format("{0}.{1}.db3", task.Schema, table));
lock (_locks[task.Schema])
{
task.OnRowsInserted(CopyEventType.Processing, "Merging...");
using (SQLiteConnection conn = new SQLiteConnection(GetConnectionString(_targetPath, task.Schema)))
{
conn.Open();
SQLiteCommand cmd = conn.CreateCommand();
cmd.CommandText = Pragma;
cmd.ExecuteNonQuery();
try
{
cmd.CommandText = string.Format("ATTACH DATABASE \"{1}\" as [tmp{0}]", table, sourcePath);
cmd.ExecuteNonQuery();
using (SQLiteTransaction tx = conn.BeginTransaction())
{
DataTable tableInfo = conn.GetSchema("Columns", new[] {"tmp" + table, null, table + "_tmp"});
string columnList = string.Join(",",
tableInfo.Select().Select(r => r["COLUMN_NAME"]).Cast
<string>().
ToArray());
cmd.CommandText = string.Format(transferFormat, table, columnList);
cmd.ExecuteNonQuery();
tx.Commit();
}
cmd.CommandText = string.Format("DETACH DATABASE [tmp{0}]", table);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
task.OnRowsInserted(CopyEventType.Error, ex.Message);
return;
}
Thread.Sleep(100);
File.Delete(sourcePath);
}
}
}
示例12: ListTableColumns
private static List<string> ListTableColumns(SQLiteConnection connection, string tableName)
{
List<string> returnList = new List<string>();
string[] restrictionValues =
{
null,
null,
tableName,
null
};
DataTable columns = connection.GetSchema(System.Data.SQLite.SQLiteMetaDataCollectionNames.Columns, restrictionValues);
foreach (DataRow columnRow in columns.Rows)
{
returnList.Add(columnRow["COLUMN_NAME"].ToString());
}
return returnList;
}
示例13: SQLiteKeyReader
/// <summary>
/// This function does all the nasty work at determining what keys need to be returned for
/// a given statement.
/// </summary>
/// <param name="cnn"></param>
/// <param name="reader"></param>
/// <param name="stmt"></param>
internal SQLiteKeyReader(SQLiteConnection cnn, SQLiteDataReader reader, SQLiteStatement stmt)
{
Dictionary<string, int> catalogs = new Dictionary<string, int>();
Dictionary<string, List<string>> tables = new Dictionary<string, List<string>>();
List<string> list;
List<KeyInfo> keys = new List<KeyInfo>();
// Record the statement so we can use it later for sync'ing
_stmt = stmt;
// Fetch all the attached databases on this connection
using (DataTable tbl = cnn.GetSchema("Catalogs"))
{
foreach (DataRow row in tbl.Rows)
{
catalogs.Add((string)row["CATALOG_NAME"], Convert.ToInt32(row["ID"], CultureInfo.InvariantCulture));
}
}
// Fetch all the unique tables and catalogs used by the current statement
using (DataTable schema = reader.GetSchemaTable(false, false))
{
foreach (DataRow row in schema.Rows)
{
// Check if column is backed to a table
if (row[SchemaTableOptionalColumn.BaseCatalogName] == DBNull.Value)
continue;
// Record the unique table so we can look up its keys
string catalog = (string)row[SchemaTableOptionalColumn.BaseCatalogName];
string table = (string)row[SchemaTableColumn.BaseTableName];
if (tables.ContainsKey(catalog) == false)
{
list = new List<string>();
tables.Add(catalog, list);
}
else
list = tables[catalog];
if (list.Contains(table) == false)
list.Add(table);
}
// For each catalog and each table, query the indexes for the table.
// Find a primary key index if there is one. If not, find a unique index instead
foreach (KeyValuePair<string, List<string>> pair in tables)
{
for (int i = 0; i < pair.Value.Count; i++)
{
string table = pair.Value[i];
DataRow preferredRow = null;
using (DataTable tbl = cnn.GetSchema("Indexes", new string[] { pair.Key, null, table }))
{
// Loop twice. The first time looking for a primary key index,
// the second time looking for a unique index
for (int n = 0; n < 2 && preferredRow == null; n++)
{
foreach (DataRow row in tbl.Rows)
{
if (n == 0 && (bool)row["PRIMARY_KEY"] == true)
{
preferredRow = row;
break;
}
else if (n == 1 && (bool)row["UNIQUE"] == true)
{
preferredRow = row;
break;
}
}
}
if (preferredRow == null) // Unable to find any suitable index for this table so remove it
{
pair.Value.RemoveAt(i);
i--;
}
else // We found a usable index, so fetch the necessary table details
{
using (DataTable tblTables = cnn.GetSchema("Tables", new string[] { pair.Key, null, table }))
{
// Find the root page of the table in the current statement and get the cursor that's iterating it
int database = catalogs[pair.Key];
int rootPage = Convert.ToInt32(tblTables.Rows[0]["TABLE_ROOTPAGE"], CultureInfo.InvariantCulture);
int cursor = stmt._sql.GetCursorForTable(stmt, database, rootPage);
// Now enumerate the members of the index we're going to use
using (DataTable indexColumns = cnn.GetSchema("IndexColumns", new string[] { pair.Key, null, table, (string)preferredRow["INDEX_NAME"] }))
{
KeyQuery query = null;
List<string> cols = new List<string>();
for (int x = 0; x < indexColumns.Rows.Count; x++)
//.........这里部分代码省略.........
示例14: IsDatabaseCreated
/// <summary>
/// Check if database has been created to opened file.
/// </summary>
private static bool IsDatabaseCreated(string path, string password)
{
string connectionString = String.Format(CultureInfo.CurrentCulture, "Data source=\"{0}\";Version=3;Password={1}", path, password);
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
using (DataTable table = connection.GetSchema("Tables"))
{
return table.Rows.Count > 0;
}
}
}
示例15: GetSchema
public static DataTable GetSchema(string collectionName)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
DataTable dt = new DataTable();
try
{
dt.Clear();
connection.Open();
dt = connection.GetSchema(collectionName);
}
catch
{
dt = null;
}
return dt;
}
}