本文整理汇总了C#中IDbConnection.GetDialect方法的典型用法代码示例。如果您正苦于以下问题:C# IDbConnection.GetDialect方法的具体用法?C# IDbConnection.GetDialect怎么用?C# IDbConnection.GetDialect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IDbConnection
的用法示例。
在下文中一共展示了IDbConnection.GetDialect方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExecuteAndGetID
/// <summary>
/// <see cref="SqlInsert"/> nesnesinin içerdiği sorguyu bağlantı üzerinde çalıştırır ve
/// istenirse eklenen kaydın IDENTITY alanının değerini döndürür.</summary>
/// <remarks>
/// <p>Bu bir extension metodu olduğundan direk query.Execute(connection, true) şeklinde de
/// çalıştırılabilir.</p></remarks>
/// <param name="query">
/// Sorguyu içeren <see cref="SqlInsert"/> nesnesi.</param>
/// <param name="connection">
/// Sorgunun çalıştırılacağı bağlantı. Gerekirse otomatik olarak açılır.</param>
/// <returns>
/// Identity value of inserted record.</returns>
public static Int64? ExecuteAndGetID(this SqlInsert query, IDbConnection connection)
{
string queryText = query.ToString();
var dialect = connection.GetDialect();
if (dialect.UseReturningIdentity || dialect.UseReturningIntoVar)
{
string identityColumn = query.IdentityColumn();
if (identityColumn == null)
throw new ArgumentNullException("query.IdentityColumn");
queryText += " RETURNING " + SqlSyntax.AutoBracket(identityColumn);
if (dialect.UseReturningIntoVar)
queryText += " INTO " + dialect.ParameterPrefix + identityColumn;
using (var command = NewCommand(connection, queryText, query.Params))
{
var param = command.CreateParameter();
param.Direction = dialect.UseReturningIntoVar ? ParameterDirection.ReturnValue : ParameterDirection.Output;
param.ParameterName = identityColumn;
param.DbType = DbType.Int64;
command.Parameters.Add(param);
ExecuteNonQuery(command);
return Convert.ToInt64(param.Value);
}
}
if (dialect.UseScopeIdentity)
{
var scopeIdentityExpression = dialect.ScopeIdentityExpression;
queryText += ";\nSELECT " + scopeIdentityExpression + " AS IDCOLUMNVALUE";
using (IDataReader reader = ExecuteReader(connection, queryText, query.Params))
{
if (reader.Read() &&
!reader.IsDBNull(0))
return Convert.ToInt64(reader.GetValue(0));
return null;
}
}
throw new NotImplementedException();
}
示例2: GenerateInsertStatements
public static string GenerateInsertStatements(IDbConnection connection, string query, string table = null)
{
if (table == null)
{
var x = query.Replace("\r", "").Replace("\n", " ");
var idx = x.IndexOf("from ", StringComparison.OrdinalIgnoreCase);
if (idx >= 0)
{
table = x.Substring(idx + 5).Trim();
idx = table.IndexOf(" ");
if (idx >= 0)
table = table.Substring(0, idx).Trim();
}
table = table ?? "SomeTable";
}
using (var reader = SqlHelper.ExecuteReader(connection, query))
return GenerateInsertStatements(reader, table, connection.GetDialect());
}
示例3: GetTableNames
public static List<TableName> GetTableNames(IDbConnection connection)
{
var query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
var tables = connection.Query(query);
bool sqlite = connection.GetDialect().ServerType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase);
if (sqlite)
query = "select name TABLE_NAME, type TABLE_TYPE, '' TABLE_SCHEMA from sqlite_master type='table' or type='view'";
var result = new List<TableName>();
foreach (IDictionary<string, object> row in tables)
{
var tableType = row["TABLE_TYPE"] as string;
var schema = row["TABLE_SCHEMA"] as string;
var tableName = row["TABLE_NAME"] as string;
result.Add(new TableName { Schema = schema, Table = tableName });
}
return result.OrderBy(x => x.Schema).ThenBy(x => x.Table).ToList();
}
示例4: UpdateOrders
public static bool UpdateOrders(IDbConnection connection, List<OrderRecord> orderRecords,
string tableName, Field keyField, Field orderField, bool hasUniqueConstraint = false)
{
if (connection == null)
throw new ArgumentNullException("connection");
if (tableName.IsEmptyOrNull())
throw new ArgumentNullException("tableName");
if (ReferenceEquals(null, keyField))
throw new ArgumentNullException("keyField");
if (ReferenceEquals(null, orderField))
throw new ArgumentNullException("orderField");
// StringBuilder that will contain query(s)
StringBuilder queries = new StringBuilder();
if (connection.GetDialect().NeedsExecuteBlockStatement)
{
queries.AppendLine("EXECUTE BLOCK AS");
queries.AppendLine("BEGIN");
}
int updateCount = 0;
Action<long, long> appendSingleUpdate = delegate(long id, long newOrder)
{
queries.AppendLine(String.Format(
"UPDATE {0} SET {1} = {2} WHERE {3} = {4};", tableName,
orderField.Name, newOrder, keyField.Name, id));
updateCount++;
};
if (hasUniqueConstraint)
{
var byCurrentOrder = new Dictionary<Int64, OrderRecord>();
foreach (var rec in orderRecords)
byCurrentOrder[rec.oldOrder] = rec;
var list = new List<OrderRecord>();
list.AddRange(orderRecords);
list.Sort((x, y) => (x.newOrder - y.newOrder));
foreach (var rec in list)
{
if (rec.oldOrder != rec.newOrder)
{
byCurrentOrder.Remove(rec.oldOrder);
OrderRecord congestion;
if (byCurrentOrder.TryGetValue(rec.newOrder, out congestion))
{
var empty = list.Count * 2;
while (byCurrentOrder.ContainsKey(empty))
empty++;
congestion.oldOrder = empty;
appendSingleUpdate(congestion.recordID, empty);
byCurrentOrder[empty] = congestion;
}
appendSingleUpdate(rec.recordID, rec.newOrder);
byCurrentOrder[rec.newOrder] = rec;
}
}
}
else
{
// StringBuilder that will contain IN(...) part of the latest query
StringBuilder sb = new StringBuilder();
// scan all display order changing records
int start = 0;
while (start < orderRecords.Count)
{
OrderRecord rs = orderRecords[start];
// if this records display order is not changed, skip it
if (rs.oldOrder == rs.newOrder)
{
start++;
continue;
}
// find the difference between old and new display orders
int difference = rs.oldOrder - rs.newOrder;
// clear the IN(...) list
sb.Length = 0;
// add this records ID to the IN (...) part
sb.Append(rs.recordID);
// now we'll find all following records whose display orders are changed same amount
// (difference between old and new is same), so we will update them with just one query
// like UPDATE ORDER = ORDER + 1 WHERE ID IN (X, Y, Z....).
int finish = start;
while (finish + 1 < orderRecords.Count)
//.........这里部分代码省略.........
示例5: NewCommand
/// <summary>
/// İstenen bağlantıya bağlı ve verilen komutu içeren yeni bir IDbCommand nesnesi oluşturur.</summary>
/// <param name="connection">
/// IDbCommand nesnesinin oluşturulacağı bağlantı.</param>
/// <param name="commandText">
/// IDbCommand nesnesinin içereceği komut metni. <c>null</c> olabilir.</param>
/// <returns>
/// Yeni IDbCommand nesnesi.</returns>
public static IDbCommand NewCommand(IDbConnection connection, string commandText)
{
if (connection == null)
throw new ArgumentNullException("connection");
IDbCommand command = connection.CreateCommand();
commandText = DatabaseCaretReferences.Replace(commandText);
var dialect = connection.GetDialect();
var openBracket = dialect.OpenQuote;
if (openBracket != '[')
commandText = BracketLocator.ReplaceBrackets(commandText, dialect);
command.CommandText = commandText;
return command;
}
示例6: GetTablePrimaryFields
public static List<string> GetTablePrimaryFields(IDbConnection connection, string schema, string tableName)
{
var inf = InformationSchema(connection);
List<string> primaryFields = new List<string>();
if (connection.GetDialect().ServerType == "Firebird")
{
var query = @"
select
cast(RC.RDB$RELATION_NAME as varchar(31)) as TABLE_NAME,
cast(ISGMT.RDB$FIELD_NAME as varchar(31)) as COLUMN_NAME,
CAST((ISGMT.RDB$FIELD_POSITION + 1) as SMALLINT) as KEY_SEQ,
cast(RC.RDB$CONSTRAINT_NAME as varchar(31)) as PK_NAME
from
RDB$RELATION_CONSTRAINTS RC
INNER JOIN RDB$INDEX_SEGMENTS ISGMT ON RC.RDB$INDEX_NAME = ISGMT.RDB$INDEX_NAME
where CAST(RC.RDB$RELATION_NAME AS VARCHAR(40)) = '{0}' and
RC.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
order by 3";
foreach (var k in connection.Query(String.Format(query, tableName)))
{
primaryFields.Add(((string)k.COLUMN_NAME).TrimEnd());
}
return primaryFields;
}
var columns = ((DbConnection)((WrappedConnection)connection).ActualConnection).GetSchema("Columns", new string[] { null, schema, tableName, null });
if (columns.Columns.Contains("PRIMARY_KEY"))
{
foreach (DataRow row in columns.Rows)
{
try
{
var isPrimaryKey = row["PRIMARY_KEY"] as Boolean?;
if (isPrimaryKey == true)
primaryFields.Add((string)row["COLUMN_NAME"]);
}
catch (Exception)
{
}
}
return primaryFields;
}
if (connection.GetDialect().ServerType.StartsWith("MySql", StringComparison.OrdinalIgnoreCase) ||
connection.GetDialect().ServerType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase))
{
var query = new SqlQuery().Select(
"KCU.COLUMN_NAME")
.From(
inf + "TABLE_CONSTRAINTS AS TC INNER JOIN " +
inf + "KEY_COLUMN_USAGE AS KCU " +
"ON KCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA AND " +
"KCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME AND " +
"KCU.TABLE_SCHEMA = TC.TABLE_SCHEMA AND " +
"KCU.TABLE_NAME = TC.TABLE_NAME")
.Where(
new Criteria("TC.CONSTRAINT_TYPE") == "PRIMARY KEY" &
new Criteria("KCU.TABLE_NAME") == tableName)
.OrderBy(
"KCU.ORDINAL_POSITION");
query.ForEach(connection, delegate(IDataReader reader)
{
primaryFields.Add(reader.GetString(0));
});
}
return primaryFields;
}
示例7: GetTableSingleFieldForeignKeys
public static List<ForeignKeyInfo> GetTableSingleFieldForeignKeys(IDbConnection connection, string schema, string tableName)
{
var inf = InformationSchema(connection);
List<ForeignKeyInfo> foreignKeyInfos = new List<ForeignKeyInfo>();
if (connection.GetDialect().ServerType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase))
{
try
{
using (var reader =
SqlHelper.ExecuteReader(connection,
(String.Format("PRAGMA foreign_key_list({0});", tableName))))
{
while (reader.Read())
{
ForeignKeyInfo foreignKeyInfo = new ForeignKeyInfo();
foreignKeyInfo.FKTable = tableName;
foreignKeyInfo.FKColumn = reader.GetString(3);
foreignKeyInfo.PKTable = reader.GetString(2);
foreignKeyInfo.PKColumn = reader.GetString(4);
foreignKeyInfos.Add(foreignKeyInfo);
}
}
}
catch (Exception)
{
}
return foreignKeyInfos;
}
if (connection.GetDialect().ServerType.StartsWith("Firebird", StringComparison.OrdinalIgnoreCase))
{
var query = @"
select
PK.RDB$RELATION_NAME as PKTABLE_NAME
,ISP.RDB$FIELD_NAME as PKCOLUMN_NAME
,FK.RDB$RELATION_NAME as FKTABLE_NAME
,ISF.RDB$FIELD_NAME as FKCOLUMN_NAME
,(ISP.RDB$FIELD_POSITION + 1) as KEY_SEQ
,RC.RDB$UPDATE_RULE as UPDATE_RULE
,RC.RDB$DELETE_RULE as DELETE_RULE
,PK.RDB$CONSTRAINT_NAME as PK_NAME
,FK.RDB$CONSTRAINT_NAME as FK_NAME
from
RDB$RELATION_CONSTRAINTS PK
,RDB$RELATION_CONSTRAINTS FK
,RDB$REF_CONSTRAINTS RC
,RDB$INDEX_SEGMENTS ISP
,RDB$INDEX_SEGMENTS ISF
WHERE FK.RDB$RELATION_NAME = '{0}' and
FK.RDB$CONSTRAINT_NAME = RC.RDB$CONSTRAINT_NAME
and PK.RDB$CONSTRAINT_NAME = RC.RDB$CONST_NAME_UQ
and ISP.RDB$INDEX_NAME = PK.RDB$INDEX_NAME
and ISF.RDB$INDEX_NAME = FK.RDB$INDEX_NAME
and ISP.RDB$FIELD_POSITION = ISF.RDB$FIELD_POSITION
order by 1, 5";
try
{
using (var reader =
SqlHelper.ExecuteReader(connection,
(String.Format(query, tableName))))
{
while (reader.Read())
{
ForeignKeyInfo foreignKeyInfo = new ForeignKeyInfo();
foreignKeyInfo.FKTable = tableName;
foreignKeyInfo.FKColumn = reader.GetString(3).TrimEnd();
foreignKeyInfo.PKTable = reader.GetString(0).TrimEnd();
foreignKeyInfo.PKColumn = reader.GetString(1).TrimEnd();
foreignKeyInfos.Add(foreignKeyInfo);
}
}
}
catch (Exception)
{
}
return foreignKeyInfos;
}
if (connection.GetDialect().ServerType.StartsWith("Postgres", StringComparison.OrdinalIgnoreCase))
{
try
{
var list = connection.Query(
@"SELECT * FROM (
SELECT
o.conname AS constraint_name,
(SELECT nspname FROM pg_namespace WHERE oid=m.relnamespace) AS source_schema,
m.relname AS source_table,
(SELECT a.attname FROM pg_attribute a WHERE a.attrelid = m.oid AND a.attnum = o.conkey[1] AND a.attisdropped = false) AS source_column,
(SELECT nspname FROM pg_namespace WHERE oid=f.relnamespace) AS target_schema,
f.relname AS target_table,
(SELECT a.attname FROM pg_attribute a WHERE a.attrelid = f.oid AND a.attnum = o.confkey[1] AND a.attisdropped = false) AS target_column
//.........这里部分代码省略.........
示例8: GetTableIdentityFields
public static List<string> GetTableIdentityFields(IDbConnection connection, string schema, string tableName)
{
var columns = ((DbConnection)((WrappedConnection)connection).ActualConnection).GetSchema("Columns", new string[] { null, schema, tableName, null });
List<string> identityFields = new List<string>();
if (connection.GetDialect().ServerType.StartsWith("Firebird", StringComparison.OrdinalIgnoreCase))
{
return new List<string>();
}
if (connection.GetDialect().ServerType.StartsWith("Postgres", StringComparison.OrdinalIgnoreCase))
{
foreach (DataRow row in columns.Rows)
{
var defaultValue = row["column_default"] as string;
if (defaultValue != null && defaultValue.IndexOf("nextval(") > 0)
identityFields.Add((string)row["COLUMN_NAME"]);
}
return identityFields;
}
if (connection.GetDialect().ServerType.StartsWith("MySql", StringComparison.OrdinalIgnoreCase))
{
foreach (DataRow row in columns.Rows)
{
var isIdentity = (row["EXTRA"] as string) == "auto_increment";
if (isIdentity == true)
identityFields.Add((string)row["COLUMN_NAME"]);
}
return identityFields;
}
if (columns.Columns.Contains("AUTOINCREMENT"))
{
foreach (DataRow row in columns.Rows)
{
var isIdentity = row["AUTOINCREMENT"] as Boolean?;
if (isIdentity == true)
identityFields.Add((string)row["COLUMN_NAME"]);
}
return identityFields;
}
if (connection.GetDialect().ServerType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase))
{
new SqlQuery().Select(
"C.NAME")
.From(
"syscolumns C " +
"LEFT OUTER JOIN sysobjects T " +
"ON (C.id = T.id)")
.Where(
new Criteria("C.STATUS & 128") == 128 &
new Criteria("T.NAME") == tableName &
new Criteria("T.XTYPE") == "U")
.ForEach(connection, delegate (IDataReader reader)
{
identityFields.Add(reader.GetString(0));
});
}
return identityFields;
}
示例9: GetTablePrimaryFields
public static List<string> GetTablePrimaryFields(IDbConnection connection, string schema, string tableName)
{
var inf = InformationSchema(connection);
List<string> primaryFields = new List<string>();
if (connection.GetDialect().ServerType == "Firebird")
{
var q = @"
select
cast(RC.RDB$RELATION_NAME as varchar(31)) as TABLE_NAME,
cast(ISGMT.RDB$FIELD_NAME as varchar(31)) as COLUMN_NAME,
CAST((ISGMT.RDB$FIELD_POSITION + 1) as SMALLINT) as KEY_SEQ,
cast(RC.RDB$CONSTRAINT_NAME as varchar(31)) as PK_NAME
from
RDB$RELATION_CONSTRAINTS RC
INNER JOIN RDB$INDEX_SEGMENTS ISGMT ON RC.RDB$INDEX_NAME = ISGMT.RDB$INDEX_NAME
where CAST(RC.RDB$RELATION_NAME AS VARCHAR(40)) = '{0}' and
RC.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
order by 3";
foreach (IDictionary<string, object> k in connection.Query(String.Format(q, tableName)))
{
primaryFields.Add((k["COLUMN_NAME"] as string).TrimEnd());
}
return primaryFields;
}
var query = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE [email protected] and TABLE_NAME = @tableName";
bool sqlite = connection.GetDialect().ServerType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase);
if (sqlite)
query = "PRAGMA table_info(@tableName)";
var columns = connection.Query(query, new
{
schema,
tableName
});
foreach (IDictionary<string, object> column in columns)
{
try
{
var isPrimaryKey = column["PRIMARY_KEY"] as Boolean?;
if (isPrimaryKey == true)
primaryFields.Add(column["COLUMN_NAME"] as string);
}
catch
{
break;
}
return primaryFields;
}
if (connection.GetDialect().ServerType.StartsWith("MySql", StringComparison.OrdinalIgnoreCase) ||
connection.GetDialect().ServerType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase))
{
var query2 = new SqlQuery().Select(
"KCU.COLUMN_NAME")
.From(
inf + "TABLE_CONSTRAINTS AS TC INNER JOIN " +
inf + "KEY_COLUMN_USAGE AS KCU " +
"ON KCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA AND " +
"KCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME AND " +
"KCU.TABLE_SCHEMA = TC.TABLE_SCHEMA AND " +
"KCU.TABLE_NAME = TC.TABLE_NAME")
.Where(
new Criteria("TC.CONSTRAINT_TYPE") == "PRIMARY KEY" &
new Criteria("KCU.TABLE_NAME") == tableName)
.OrderBy(
"KCU.ORDINAL_POSITION");
query2.ForEach(connection, delegate(IDataReader reader)
{
primaryFields.Add(reader.GetString(0));
});
}
return primaryFields;
}
示例10: GetTableFieldInfos
public static List<FieldInfo> GetTableFieldInfos(IDbConnection connection, string schema, string tableName)
{
var inf = InformationSchema(connection);
List<FieldInfo> fieldInfos = new List<FieldInfo>();
List<ForeignKeyInfo> foreignKeys = GetTableSingleFieldForeignKeys(connection, schema, tableName);
List<string> primaryFields = GetTablePrimaryFields(connection, schema, tableName);
List<string> identityFields = GetTableIdentityFields(connection, schema, tableName);
var query = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE [email protected] and TABLE_NAME = @tableName";
bool sqlite = connection.GetDialect().ServerType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase);
if (sqlite)
query = "PRAGMA table_info(@tableName)";
var columns = connection.Query(query, new
{
schema,
tableName
});
var order = new Dictionary<string, int>();
if (!columns.Any())
return new List<CodeGenerator.SqlSchemaInfo.FieldInfo>();
var first = columns.First() as IDictionary<string, object>;
var ordinal = "ORDINAL_POSITION";
var columnName = "COLUMN_NAME";
var isNullable = "IS_NULLABLE";
var charMax = "CHARACTER_MAXIMUM_LENGTH";
var numPrec = "NUMERIC_PRECISION";
var numScale = "NUMERIC_SCALE";
var dataType = "DATA_TYPE";
if (!first.ContainsKey(ordinal) &&
first.ContainsKey(ordinal.ToLowerInvariant()))
{
ordinal = ordinal.ToLowerInvariant();
columnName = columnName.ToLowerInvariant();
dataType = dataType.ToLowerInvariant();
isNullable = isNullable.ToLowerInvariant();
charMax = charMax.ToLowerInvariant();
numPrec = numPrec.ToLowerInvariant();
numScale = numScale.ToLowerInvariant();
}
if (!first.ContainsKey(dataType) &&
first.ContainsKey("COLUMN_DATA_TYPE"))
dataType = "COLUMN_DATA_TYPE";
if (!first.ContainsKey(charMax) &&
first.ContainsKey("COLUMN_SIZE"))
charMax = "COLUMN_SIZE";
foreach (IDictionary<string, object> row in columns)
{
FieldInfo fieldInfo = new FieldInfo();
fieldInfo.FieldName = (string)row[columnName];
order[fieldInfo.FieldName] = Convert.ToInt32(row[ordinal]);
fieldInfo.IsPrimaryKey =
primaryFields.IndexOf(fieldInfo.FieldName) >= 0;
fieldInfo.IsIdentity =
identityFields.IndexOf(fieldInfo.FieldName) >= 0;
fieldInfo.IsNullable = (row[isNullable] as string == "YES") || (row[isNullable] as Boolean? == true);
fieldInfo.DataType = row[dataType] as string;
fieldInfo.Size = 0;
if (fieldInfo.DataType != SqlInt &&
fieldInfo.DataType != SqlInteger &&
fieldInfo.DataType != SqlReal &&
fieldInfo.DataType != SqlFloat &&
fieldInfo.DataType != SqlTinyInt &&
fieldInfo.DataType != SqlSmallInt &&
fieldInfo.DataType != SqlBigInt &&
fieldInfo.DataType != SqlInt8 &&
fieldInfo.DataType != SqlInt4)
{
var val = row[charMax];
var size = (val == null || val == DBNull.Value) ? (Int64?)null : Convert.ToInt64(val);
if (size != null && size > 0 && size <= 1000000000)
fieldInfo.Size = (int)size.Value;
val = row[numPrec];
var prec = (val == null || val == DBNull.Value) ? (Int64?)null : Convert.ToInt64(val);
string dataType2;
if (prec != null && (SqlTypeNameToFieldType(fieldInfo.DataType, fieldInfo.Size, out dataType2) != "String") &&
prec >= 0 && prec < 1000000000)
{
fieldInfo.Size = Convert.ToInt32(prec.Value);
}
val = row[numScale];
var scale = (val == null || val == DBNull.Value) ? (Int64?)null : Convert.ToInt64(val);
if (scale != null && scale >= 0 && scale < 1000000000)
fieldInfo.Scale = Convert.ToInt32(scale.Value);
}
//.........这里部分代码省略.........
示例11: GetTableFieldNames
public static List<string> GetTableFieldNames(IDbConnection connection, string schema, string tableName)
{
var inf = InformationSchema(connection);
var list = new List<string>();
var dict = new Dictionary<string, int>();
var query = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE [email protected] and TABLE_NAME = @tableName";
bool sqlite = connection.GetDialect().ServerType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase);
if (sqlite)
query = "PRAGMA table_info(@tableName)";
var columns = connection.Query(query, new
{
schema,
tableName
});
foreach (IDictionary<string, object> row in columns)
{
var col = (string)row["COLUMN_NAME"];
dict[col] = (int)row["ORDINAL_POSITION"];
list.Add(col);
}
list.Sort((x, y) => dict[x].CompareTo(dict[y]));
return list;
}
示例12: GetTableIdentityFields
public static List<string> GetTableIdentityFields(IDbConnection connection, string schema, string tableName)
{
var identityFields = new List<string>();
if (connection.GetDialect().ServerType.StartsWith("Firebird", StringComparison.OrdinalIgnoreCase))
return identityFields;
var query = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE [email protected] and TABLE_NAME = @tableName";
bool sqlite = connection.GetDialect().ServerType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase);
if (sqlite)
query = "PRAGMA table_info(@tableName)";
var columns = connection.Query(query, new
{
schema,
tableName
});
if (connection.GetDialect().ServerType.StartsWith("Postgres", StringComparison.OrdinalIgnoreCase))
{
foreach (IDictionary<string, object> row in columns)
{
var defaultValue = row["column_default"] as string;
if (defaultValue != null && defaultValue.IndexOf("nextval(") > 0)
identityFields.Add(row["COLUMN_NAME"] as string);
}
return identityFields;
}
if (connection.GetDialect().ServerType.StartsWith("MySql", StringComparison.OrdinalIgnoreCase))
{
foreach (IDictionary<string, object> row in columns)
{
var isIdentity = (row["EXTRA"] as string) == "auto_increment";
if (isIdentity == true)
identityFields.Add((string)row["COLUMN_NAME"]);
}
return identityFields;
}
foreach (IDictionary<string, object> row in columns)
{
var isIdentity = row.ContainsKey("AUTOINCREMENT") && row["AUTOINCREMENT"] as Boolean? == true;
if (isIdentity == true)
identityFields.Add((string)row["COLUMN_NAME"]);
}
if (connection.GetDialect().ServerType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase))
{
new SqlQuery().Select(
"C.NAME")
.From(
"syscolumns C " +
"LEFT OUTER JOIN sysobjects T " +
"ON (C.id = T.id)")
.Where(
new Criteria("C.STATUS & 128") == 128 &
new Criteria("T.NAME") == tableName &
new Criteria("T.XTYPE") == "U")
.ForEach(connection, delegate (IDataReader reader)
{
identityFields.Add(reader.GetString(0));
});
}
return identityFields;
}
示例13: NewCommand
/// <summary>
/// İstenen bağlantıya bağlı ve verilen komutu içeren yeni bir IDbCommand nesnesi oluşturur.</summary>
/// <param name="connection">
/// IDbCommand nesnesinin oluşturulacağı bağlantı.</param>
/// <param name="commandText">
/// IDbCommand nesnesinin içereceği komut metni. <c>null</c> olabilir.</param>
/// <param name="param">
/// Parameters.</param>
/// <returns>
/// Yeni IDbCommand nesnesi.</returns>
public static IDbCommand NewCommand(IDbConnection connection, string commandText, IDictionary<string, object> param)
{
var command = (DbCommand)(NewCommand(connection, commandText));
if (param == null || param.Count == 0)
return command;
try
{
var dialect = connection.GetDialect();
foreach (var p in param)
AddParamWithValue(command, p.Key, p.Value, dialect);
return command;
}
catch
{
command.Dispose();
throw;
}
}