当前位置: 首页>>代码示例>>C#>>正文


C# DbConnection.CreateCommand方法代码示例

本文整理汇总了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;
		}
开发者ID:epdumitru,项目名称:mysqlib,代码行数:52,代码来源:ReflectionDbFunctionHelper.cs

示例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 ("##########################");
        }
开发者ID:mono,项目名称:momareports,代码行数:13,代码来源:createmomadb.cs

示例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();
 }
开发者ID:wenysky,项目名称:reimu,代码行数:19,代码来源:DBHelper.cs

示例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);					
				}
			}
		}
开发者ID:epdumitru,项目名称:mysqlib,代码行数:41,代码来源:ReflectionDbFunctionHelper.cs

示例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;
        }
开发者ID:SwarmCorp,项目名称:Swarmops,代码行数:22,代码来源:Database-ConnectionsCommands.cs

示例6: DbAdapter

 public DbAdapter(string query, DbConnection conn)
 {
   this.SelectCommand = conn.CreateCommand();
   this.SelectCommand.CommandText = query;
 }
开发者ID:rneuber1,项目名称:InnovatorAdmin,代码行数:5,代码来源:DbAdapter.cs

示例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;
 }
开发者ID:eeeee,项目名称:mysql-connector-net,代码行数:51,代码来源:MySqlCompletionSource.cs

示例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;
     }
 }
开发者ID:quangnc0503h,项目名称:ecommerce,代码行数:10,代码来源:DataAccessBase.cs

示例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;
        }
开发者ID:SyedMdKamruzzaman,项目名称:sap_interface,代码行数:15,代码来源:netlib7.cs

示例10: GetCommand

 public DbCommand GetCommand(DbConnection connection, CommandType commandType)
 {
     DbCommand command = connection.CreateCommand();
         command.CommandType = commandType;
         return command;
 }
开发者ID:jiangxianfu,项目名称:MiniORM,代码行数:6,代码来源:Database.cs

示例11: GetStoredProcCommand

 public DbCommand GetStoredProcCommand(DbConnection connection, string storedProcedureName)
 {
     DbCommand command = connection.CreateCommand();
         command.CommandText = storedProcedureName;
         command.CommandType = CommandType.StoredProcedure;
         return command;
 }
开发者ID:jiangxianfu,项目名称:MiniORM,代码行数:7,代码来源:Database.cs

示例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;
		}
开发者ID:epdumitru,项目名称:mysqlib,代码行数:59,代码来源:ReflectionDbFunctionHelper.cs

示例13: GetCommand

        public DbCommand GetCommand(out DbConnection getcon)
        {
            getcon = ConnectDB();

            return getcon.CreateCommand();
        }
开发者ID:BCProgramming,项目名称:BCJobClock,代码行数:6,代码来源:DataLayer.cs

示例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;
        }
开发者ID:BCProgramming,项目名称:BCJobClock,代码行数:86,代码来源:DataLayer.cs

示例15: GetSqlCommand

 public DbCommand GetSqlCommand(DbConnection connection, string sql)
 {
     DbCommand command = connection.CreateCommand();
         command.CommandText = sql;
         command.CommandType = CommandType.Text;
         return command;
 }
开发者ID:jiangxianfu,项目名称:MiniORM,代码行数:7,代码来源:Database.cs


注:本文中的DbConnection.CreateCommand方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。