本文整理汇总了C#中DbConnection.CreateCommand方法的典型用法代码示例。如果您正苦于以下问题:C# DbConnection.CreateCommand方法的具体用法?C# DbConnection.CreateCommand怎么用?C# DbConnection.CreateCommand使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DbConnection
的用法示例。
在下文中一共展示了DbConnection.CreateCommand方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Update
public int Update(IDbObject o, DbConnection connection, IDictionary<IDbObject, long> objectGraph)
{
objectGraph.Add(o, o.Id);
var classMetadata = ClassMetaDataManager.Instace.GetClassMetaData(o.GetType());
var result = 0;
if (o.IsDirty)
{
o.IsDirty = false;
var mappingTable = classMetadata.MappingTable;
var properties = classMetadata.Properties;
var command = connection.CreateCommand();
var queryBuilder = new StringBuilder("UPDATE " + mappingTable + " SET ");
foreach (var mappingInfo in properties.Values)
{
var mappingField = mappingInfo.MappingField;
queryBuilder.Append("`" + mappingField + "`[email protected]" + mappingField + ", ");
}
var tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2);
queryBuilder.Length = 0;
queryBuilder.Append(tmpString);
queryBuilder.Append(" WHERE Id = " + o.Id);
command.CommandText = queryBuilder.ToString();
foreach (var mappingInfo in properties.Values)
{
var mappingField = mappingInfo.MappingField;
var propertyInfo = mappingInfo.PropertyInfo;
var propertyType = propertyInfo.PropertyType;
object value = propertyInfo.GetValue(o, null);
if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(decimal))
{
command.Parameters.Add(new MySqlParameter("@" + mappingField, value));
}
else
{
byte[] blob = null;
if (value != null)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, value);
blob = stream.ToArray();
}
}
command.Parameters.Add(new MySqlParameter("@" + mappingField, blob));
}
}
result = command.ExecuteNonQuery();
}
UpdateRelations(o, classMetadata, connection, objectGraph);
return result;
}
示例2: ExecuteStatement
static void ExecuteStatement(DbConnection cnc, string command)
{
if (String.IsNullOrEmpty (command))
return;
Console.WriteLine ("***************************");
Console.WriteLine (command);
DbCommand cmd = cnc.CreateCommand ();
cmd.CommandText = command;
int res = cmd.ExecuteNonQuery ();
Console.WriteLine ("Result: {0}", res);
Console.WriteLine ("##########################");
}
示例3: DBHelper
/// <summary>
/// ���캯��--���ط�����
/// </summary>
/// <param name="connectionstring">���ݿ�����</param>
/// <param name="databasetype">���ݿ������</param>
public DBHelper(string connectionstring, string databasetype)
{
if (databasetype == "MySql.Data.MySqlClient")
{
MyFactory = new MySqlClientFactory();
}
else
{
MyFactory = DbProviderFactories.GetFactory(databasetype);
}
MyConnection = MyFactory.CreateConnection();
MyConnection.ConnectionString = (databasetype.ToString() == "System.Data.OleDb") ? ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + GetDataPath(connectionstring) + ";") : (connectionstring);
MyCommand = MyConnection.CreateCommand();
}
示例4: UpdateRelations
private void UpdateRelations(IDbObject o, ClassMetaData classMetadata, DbConnection connection, IDictionary<IDbObject, long> objectGraph)
{
var relationProperties = classMetadata.RelationProperties;
foreach (var relation in relationProperties.Values)
{
var propertyInfo = relation.PropertyInfo;
var mappingTable = relation.MappingTable;
var persistentRelation = new List<long>();
var command = connection.CreateCommand();
string queryField;
if (relation.RelationKind == RelationInfo.RELATION_N_N)
{
command.CommandText = "SELECT `" + relation.PartnerKey + "` FROM " + mappingTable + " WHERE `" + relation.OriginalKey + "` = " + o.Id;
queryField = relation.PartnerKey;
}
else
{
command.CommandText = "SELECT Id FROM " + mappingTable + " WHERE `" + relation.OriginalKey + "` = " + o.Id;
queryField = "Id";
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
persistentRelation.Add(reader.GetInt64(reader.GetOrdinal(queryField)));
}
}
if (relation.RelationKind == RelationInfo.RELATION_1_1)
{
Update11Relation(objectGraph, o, connection, relation, command, mappingTable, persistentRelation, propertyInfo);
}
else if (relation.RelationKind == RelationInfo.RELATION_1_N)
{
Update1NRelation(objectGraph, o, connection, relation, command, mappingTable, persistentRelation, propertyInfo);
}
else if (relation.RelationKind == RelationInfo.RELATION_N_N)
{
UpdateNNRelation(objectGraph, o, connection, relation, command, mappingTable, persistentRelation, propertyInfo);
}
}
}
示例5: GetDbCommand
protected DbCommand GetDbCommand (string commandText, DbConnection connection)
{
DbCommand command = connection.CreateCommand();
if (command.GetType().FullName == "System.Data.OleDb.OleDbCommand")
{
commandText = commandText.
Replace("%ISTRUE%", string.Empty).
Replace("DISTINCT", string.Empty);
if (commandText.Contains("%ISFALSE%"))
{
throw new NotImplementedException("%ISFALSE% has not been implemented for OleDbConnections");
}
}
else
{
commandText = commandText.Replace("%ISTRUE%", "= 1");
commandText = commandText.Replace("%ISFALSE%", "= 0");
}
command.CommandText = commandText;
return command;
}
示例6: DbAdapter
public DbAdapter(string query, DbConnection conn)
{
this.SelectCommand = conn.CreateCommand();
this.SelectCommand.CommandText = query;
}
示例7: GetColumns
private List<string> GetColumns(DbConnection con, List<TableWithAlias> tables)
{
DbCommand cmd = con.CreateCommand();
// information_schema.columns is available from MySql 5.0 and up.
string sql =
@"select table_schema, table_name, column_name from information_schema.columns
where ( 1 = 1 ) and ( {0} )
order by table_schema, table_name, column_name";
bool hasDbExplicit;
cmd.CommandText = BuildWhereGetColumns( con.Database, sql, tables, out hasDbExplicit);
Dictionary<string, List<string>> dicColumns = null;
DbDataReader r = cmd.ExecuteReader();
try
{
dicColumns = BuildColumnList(r, tables.Count != 0 );
}
finally
{
r.Close();
}
List<string> columns = new List<string>();
List<string> cols = new List<string>();
if (tables.Count != 0)
{
foreach (TableWithAlias ta in tables)
{
string key = string.Format("{0}.{1}",
!string.IsNullOrEmpty( ta.Database )? ta.Database : con.Database.ToLower(), ta.TableName);
// use db only if no alias defined and db was explicitely used.
string tblTempl = (hasDbExplicit && string.IsNullOrEmpty(ta.Alias)) ? "`{0}`.`{1}`.`{2}`" : "`{1}`.`{2}`";
dicColumns.TryGetValue(key, out cols);
foreach (string col in cols)
{
columns.Add(string.Format(tblTempl, ta.Database,
!string.IsNullOrEmpty(ta.Alias) ? ta.Alias : ta.TableName, col));
}
}
}
else
{
string tblTempl = "`{0}`.`{1}`";
foreach ( KeyValuePair<string, List<string>> kvp in dicColumns)
{
foreach (string s in kvp.Value)
{
columns.Add( string.Format( tblTempl, kvp.Key, s ));
}
}
}
return columns;
}
示例8: SetReadUncommitted
private static async Task<int> SetReadUncommitted(DbConnection conn)
{
return 1;
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
await cmd.ExecuteNonQueryAsync();
return 1;
}
}
示例9: CreateCommand
/// <summary>
/// Create a new command for the specified connection and command text
/// </summary>
public DbCommand CreateCommand(DbConnection connectionObject, string sqlCommandText)
{
DbCommand cm = connectionObject.CreateCommand();
cm.CommandTimeout = timeOut;
if (sqlCommandText != "")
{
cm.CommandText = sqlCommandText;
cm.CommandType = CommandType.Text;
}
return cm;
}
示例10: GetCommand
public DbCommand GetCommand(DbConnection connection, CommandType commandType)
{
DbCommand command = connection.CreateCommand();
command.CommandType = commandType;
return command;
}
示例11: GetStoredProcCommand
public DbCommand GetStoredProcCommand(DbConnection connection, string storedProcedureName)
{
DbCommand command = connection.CreateCommand();
command.CommandText = storedProcedureName;
command.CommandType = CommandType.StoredProcedure;
return command;
}
示例12: Insert
public long Insert(IDbObject o, DbConnection connection, IDictionary<IDbObject, long> objectGraph)
{
if (o.Id > 0)
{
return o.Id;
}
objectGraph.Add(o, 0);
var classMetadata = ClassMetaDataManager.Instace.GetClassMetaData(o.GetType());
var result = 0;
var mappingTable = classMetadata.MappingTable;
var properties = classMetadata.Properties;
var command = connection.CreateCommand();
var queryBuilder = new StringBuilder("INSERT INTO " + mappingTable + " ( ");
foreach (var mappingInfo in properties.Values)
{
var mappingField = mappingInfo.MappingField;
queryBuilder.Append("`" + mappingField + "`, ");
}
var tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2);
queryBuilder.Length = 0;
queryBuilder.Append(tmpString + ") VALUES (");
foreach (var mappingInfo in properties.Values)
{
var mappingField = mappingInfo.MappingField;
queryBuilder.Append("@" + mappingField + ", ");
}
tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2);
queryBuilder.Length = 0;
queryBuilder.Append(tmpString + "); SELECT LAST_INSERT_ID()");
command.CommandText = queryBuilder.ToString();
foreach (var mappingInfo in properties.Values)
{
var mappingField = mappingInfo.MappingField;
var propertyInfo = mappingInfo.PropertyInfo;
var propertyType = propertyInfo.PropertyType;
object value = propertyInfo.GetValue(o, null);
if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(decimal))
{
command.Parameters.Add(new MySqlParameter("@" + mappingField, value));
}
else
{
byte[] blob = null;
if (value != null)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, value);
blob = stream.ToArray();
}
}
command.Parameters.Add(new MySqlParameter("@" + mappingField, blob));
}
}
o.Id = (long) command.ExecuteScalar();
UpdateRelations(o, classMetadata, connection, objectGraph);
return o.Id;
}
示例13: GetCommand
public DbCommand GetCommand(out DbConnection getcon)
{
getcon = ConnectDB();
return getcon.CreateCommand();
}
示例14: ConnectDB
private DbConnection ConnectDB()
{
if (CacheCon == null)
{
try
{
WriteDebugMessage("Connecting to " + CurrentConString);
//CacheCon = new MySqlConnection(CurrentConString);
CacheCon = CreateInnerConnection(CurrentConString);
CacheCon.Open();
}
catch (Exception ex)
{
//throw new ApplicationException("Database connection failed- Connection String:\"" + CurrentConString + "\"; inner exception Message:\"" + ex.Message);
WriteDebugMessage("Exception:" + GetExceptionData(ex));
throw;
}
//Also, select the JobClockDB, for MySQL connections...
//add a handler to the INI file, this is an attempt to allow for configuration information to be persisted back and forth to and from the db.
//JobClockConfig.OurINI.BeforeRetrieveValue += new INIFile.RetrieveValueFunc(OurINI_BeforeRetrieveValue);
//JobClockConfig.OurINI.BeforeSetValue += new INIFile.SetValueFunc(OurINI_BeforeSetValue);
if (Configuration.DatabaseType.ToUpper().Trim() == "MYSQL")
{
String seldb = Configuration.DatabaseName;
DbCommand seldbcmd = CacheCon.CreateCommand();
seldbcmd.CommandText = "USE `" + seldb + "`";
try
{
seldbcmd.ExecuteNonQuery(); //yip!
//clear empty messages.
// String clearempty = "DELETE FROM MESSAGELOG WHERE TRIM(Message)=\"\"";
//seldbcmd.CommandText = clearempty;
// seldbcmd.ExecuteNonQuery();
UpdateUserTableAddActiveField();
}
catch (Exception dbexception)
{
//exception...
WriteDebugMessage("Error USE-ing Database named \"" + seldb + "\"; Error:" + dbexception.ToString());
}
}
}
else
{
//if it's not null, verify that it is still valid, otherwise we could get a "MySQL Server has gone away" exception
// when an attempt is made to execute.
//we verify that it is still alive by issuing a simple command (SELECT 1), and catching the error that will occur
//if the connection is dead.
try
{
DbCommand issueselect = CacheCon.CreateCommand();
issueselect.CommandText = "SELECT 1";
issueselect.ExecuteNonQuery();
}
catch (MySqlException mse)
{
//bugfix Jan 12 2012 8:15 AM: not responding error
if(mse.Message.Contains("gone away"))
{
//close, and re-open.
//we set the value to null and call this routine recursively,haha.
CacheCon = null;
//CacheCon will now be set in the recursive call, too.
return ConnectDB();
}
else
{
LogAdmin("Unexpected MySqlException:" + mse.ToString());
}
}
}
return CacheCon;
}
示例15: GetSqlCommand
public DbCommand GetSqlCommand(DbConnection connection, string sql)
{
DbCommand command = connection.CreateCommand();
command.CommandText = sql;
command.CommandType = CommandType.Text;
return command;
}