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


C# Connection.ExecuteNonQuery方法代码示例

本文整理汇总了C#中Connection.ExecuteNonQuery方法的典型用法代码示例。如果您正苦于以下问题:C# Connection.ExecuteNonQuery方法的具体用法?C# Connection.ExecuteNonQuery怎么用?C# Connection.ExecuteNonQuery使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Connection的用法示例。


在下文中一共展示了Connection.ExecuteNonQuery方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Run

        public bool Run()
        {
            bool result = true;

            PerformStepInvoke("Iniciando base de dados local ...");

            string line = null;
            double progress = 0;
            double progressValue = 0;
            try
            {
                //-------------------------------------------------------------------------
                // Ajustar a conexão no Unimake.Data.Generic de acordo com os dados informados na tela anterior
                //-------------------------------------------------------------------------
                Unimake.Data.Generic.Configuration.DataGenericSettings.Settings.ConnectionStrings.Add(new Unimake.Data.Generic.Configuration.ConnectionString
                {
                    DatabaseType = CurrentConfig.ServerConfig.DatabaseType,
                    ConnectionString = CurrentConfig.ServerConfig.ToConnectionString(),
                    Name = "Setup"
                });
                Unimake.Data.Generic.Configuration.DataGenericSettings.ChangeConnection("Setup");

                if(!CreateDatabase())
                {
                    MessageBox.ShowError("Não foi possível criar a base de dados. O instalador não irá continuar.");
                    return false;
                }

                Connection = DbContext.CreateConnection();
                Connection.BeginTransaction();

                #region Endereços ...
                InitInstallEnd(Connection);
                #endregion

                result = RunPreInstall(Connection);

                if(result)
                {

                    #region create table
                    string[] linesCreate = null;
                    string[] linesInsert = null;

                    using(StreamReader sr = CreateFile.OpenText())
                    {
                        line = sr.ReadToEnd();
                        linesCreate = line.Split(new string[] { ";" + "\r\n", ";" + "\n" }, StringSplitOptions.RemoveEmptyEntries);
                    }

                    line = "";
                    #endregion

                    #region insert
                    using(StreamReader sr = InsertFile.OpenText())
                    {
                        line = sr.ReadToEnd();
                        linesInsert = line.Split(new string[] { ";" + "\r\n", ";" + "\n" }, StringSplitOptions.RemoveEmptyEntries);
                    }

                    line = "";
                    #endregion

                    //-------------------------------------------------------------------------
                    // Ao final, some todas as ações extras que deverão ser realizadas
                    // Tipo de Usuário  : +2 (Administrador e Operador)
                    //-------------------------------------------------------------------------
                    progress = 100 / (double)(linesCreate.Length + linesInsert.Length + 3);

                    #region execute
                    foreach(string l in linesCreate)
                    {
                        line = l;
                        //-------------------------------------------------------------------------
                        // Algumas tabelas são ignoradas por serem pesadas na importação
                        // Então já foram previamente criadas
                        //-------------------------------------------------------------------------
                        if(IgnoreTables(line)) continue;

                        PerformStepInvoke("Executando comando: " + line);
                        Connection.ExecuteNonQuery(line);
                        ProgressInvoke((int)(progressValue += progress));
                        Application.DoEvents();
                    }

                    foreach(string l in linesInsert)
                    {
                        line = l;
                        PerformStepInvoke("Executando comando: " + line);
                        Connection.ExecuteNonQuery(line);
                        ProgressInvoke((int)(progressValue += progress));
                        Application.DoEvents();
                    }
                    #endregion

                    result = RunPostInstall(Connection);

                    Settings.Tables = Tables.GetTables(Connection);

                    #region Outras ações
//.........这里部分代码省略.........
开发者ID:njmube,项目名称:openposbr,代码行数:101,代码来源:DbInstallBase.cs

示例2: ApplyAllDescriptions

        public void ApplyAllDescriptions(List<ExtractedTableMap> tables, List<Trigger> triggers, List<Generator> generators, List<IdentityField> identities, List<View> views, List<StoredProcedure> procedures, Connection conn)
        {
            Type t;
            PropertyInfo pi;
            for(int x=0;x<_createDescriptions.Count;x++)
            {
                string str = _createDescriptions[x];
                bool remove = false;
                switch (str.Split(':')[0])
                {
                    case "ENUM":
                    case "TBL":
                    case "ITMD":
                        foreach (ExtractedTableMap etm in tables)
                        {
                            if (etm.TableName == _nameTranslations[str])
                            {
                                conn.ExecuteNonQuery(conn.queryBuilder.SetTableDescription(etm.TableName, str));
                                remove = true;
                                break;
                            }
                        }
                        break;
                    case "FLD":
                        foreach (ExtractedTableMap etm in tables)
                        {
                            t = _pool.Mapping[etm.TableName];
                            if (t != null)
                            {
                                if (str.StartsWith(string.Format(_FIELD_DESCRIPTION, t.FullName, "")))
                                {
                                    foreach (ExtractedFieldMap efm in etm.Fields)
                                    {
                                        if (_nameTranslations[str] == efm.FieldName)
                                        {
                                            conn.ExecuteNonQuery(conn.queryBuilder.SetFieldDescription(etm.TableName, efm.FieldName, str));
                                            remove = true;
                                            break;
                                        }
                                    }
                                    if (remove)
                                        break;
                                }
                            }
                        }
                        break;
                    case "ITMD_FLD":
                        foreach (ExtractedTableMap etm in tables)
                        {
                            t = _pool.Mapping.GetTypeForIntermediateTable(etm.TableName, out pi);
                            if (t != null)
                            {
                                if (str.StartsWith(string.Format(_INTERMEDIATE_FIELD_DESCRIPTION, new object[] { t.FullName, pi.Name, "",""}).Trim('.')))
                                {
                                    foreach (ExtractedFieldMap efm in etm.Fields)
                                    {
                                        if (_nameTranslations[str] == efm.FieldName)
                                        {
                                            conn.ExecuteNonQuery(conn.queryBuilder.SetFieldDescription(etm.TableName, efm.FieldName, str));
                                            remove = true;
                                            break;
                                        }
                                    }
                                    if (remove)
                                        break;
                                }
                            }
                        }
                        break;
                    case "GEN":
                        foreach (Generator gen in generators)
                        {
                            if (gen.Name == _nameTranslations[str])
                            {
                                conn.ExecuteNonQuery(conn.queryBuilder.SetGeneratorDescription(gen.Name, str));
                                remove = true;
                                break;
                            }
                        }
                        break;
                    case "TRIG":
                        foreach (Trigger trig in triggers)
                        {
                            if (trig.Name == _nameTranslations[str])
                            {
                                conn.ExecuteNonQuery(conn.queryBuilder.SetTriggerDescription(trig.Name, str));
                                remove = true;
                                break;
                            }
                        }
                        break;
                    case "VIEW":
                        foreach (View vw in views)
                        {
                            if (vw.Name == _nameTranslations[str])
                            {
                                conn.ExecuteNonQuery(conn.queryBuilder.SetViewDescription(vw.Name, str));
                                remove = true;
                                break;

//.........这里部分代码省略.........
开发者ID:marquismark,项目名称:dbpro-orm,代码行数:101,代码来源:NameTranslator.cs

示例3: InstallEnd

        protected internal virtual void InstallEnd(Connection connection)
        {
            try
            {
                //abrir o arquivo de endereços
                FileInfo dbEnderecoFile = new FileInfo(CurrentConfig.CurrentDirectory + @"\database\Endereco.sql");
                double progressValue = 0;
                double progress = 0;

            #if DEBUG
                //Desativar o log para evitar erros de outOfMemory em modo debug
                Debug.Deactivate();
            #endif
                using(StreamReader reader = new StreamReader(dbEnderecoFile.FullName))
                {
                    string line = "";
                    while((line = reader.ReadLine()) != null)
                    {
                        connection.ExecuteNonQuery(line);
                        progress = ((progressValue += line.Length) / dbEnderecoFile.Length * 100);
                        ProgressInvoke((int)progress);
                        Application.DoEvents();
                        if(CurrentConfig.CancelInstallation) throw new Exception("A instalação foi cancelada.");
                    }
                }
            }
            finally
            {
            #if DEBUG
                Debug.Activate();
            #endif
            }
        }
开发者ID:njmube,项目名称:openposbr,代码行数:33,代码来源:DbInstallBase.cs

示例4: _UpdateStructure


//.........这里部分代码省略.........
            foreach (Trigger trig in createTriggers)
            {
                alterations.Add(conn.queryBuilder.CreateTrigger(trig));
            }
            alterations.Add(_COMMIT_STRING);

            foreach (IdentityField idf in createIdentities)
                alterations.Add(conn.queryBuilder.CreateIdentityField(idf));
            alterations.Add(_COMMIT_STRING);

            foreach (IdentityField idf in setIdentities)
                alterations.Add(conn.queryBuilder.SetIdentityFieldValue(idf));
            alterations.Add(_COMMIT_STRING);

            for (int x = 0; x < alterations.Count; x++)
            {
                if (alterations[x].Contains(";ALTER")&&!alterations[x].StartsWith("CREATE TRIGGER")
                    && !alterations[x].StartsWith("ALTER TRIGGER"))
                {
                    string tmp = alterations[x];
                    alterations.RemoveAt(x);
                    alterations.Insert(x, tmp.Substring(0, tmp.IndexOf(";ALTER") + 1));
                    alterations.Insert(x + 1, tmp.Substring(tmp.IndexOf(";ALTER") + 1));
                }
                else if (alterations[x].Contains(";\nALTER") && !alterations[x].StartsWith("CREATE TRIGGER")
                    && !alterations[x].StartsWith("ALTER TRIGGER"))
                {
                    string tmp = alterations[x];
                    alterations.RemoveAt(x);
                    alterations.Insert(x, tmp.Substring(0, tmp.IndexOf(";\nALTER") + 1));
                    alterations.Insert(x + 1, tmp.Substring(tmp.IndexOf(";\nALTER") + 1));
                }
                if (alterations[x].StartsWith("ALTER") && !alterations[x].TrimEnd(new char[] { '\n', ' ', '\t' }).EndsWith(";"))
                {
                    alterations[x] = alterations[x] + ";";
                }
            }

            Utility.RemoveDuplicateStrings(ref alterations, new string[] { _COMMIT_STRING });
            for (int x = 0; x < alterations.Count; x++)
            {
                if (x + 1 < alterations.Count)
                {
                    if (alterations[x + 1].Trim() == alterations[x].Trim() && alterations[x].Trim() == "COMMIT;")
                    {
                        alterations.RemoveAt(x);
                        x--;
                    }
                }
            }

            if (!Utility.OnlyContains(alterations,new string[]{_COMMIT_STRING}))
            {
                if (alterations[0].Trim() == _COMMIT_STRING)
                    alterations.RemoveAt(0);
                try
                {
                    if (_pool.DebugMode)
                    {
                        foreach (string str in alterations)
                        {
                            if (!str.EndsWith(";"))
                                Logger.LogLine(str + ";");
                            else
                                Logger.LogLine(str);
                        }
                    }
                    else
                    {
                        foreach (string str in alterations)
                        {
                            if (str.Length > 0)
                            {
                                if (str == _COMMIT_STRING)
                                    conn.Commit();
                                else if (str.EndsWith(_COMMIT_STRING))
                                {
                                    conn.ExecuteNonQuery(str.Substring(0, str.Length - 8));
                                    conn.Commit();
                                }
                                else
                                    conn.ExecuteNonQuery(str);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.LogLine(e.Message);
                    Logger.LogLine(e.StackTrace);
                    throw e;
                }
            }
            conn.Commit();
            conn.Reset();
            _pool.Translator.ApplyAllDescriptions(tables, triggers, generators, identities, views, procedures,conn);
            conn.Commit();

            return ret;
        }
开发者ID:marquismark,项目名称:dbpro-orm,代码行数:101,代码来源:StructureUpdater.cs

示例5: CreateDatabase

        protected internal override bool CreateDatabase()
        {
            bool result = true;
            string createDatabase = "";

            //se for setup, criar a base de dados no pgsql
            if(CurrentConfig.TipoInstalacao == Enuns.TipoInstalacao.ServidorPostgreSQL)
            {
                Connection connection = new Connection(
                    CurrentConfig.ServerConfig.DatabaseType,
                    "",
                    CurrentConfig.ServerConfig.Server,
                    CurrentConfig.ServerConfig.Port,
                    CurrentConfig.ServerConfig.UserId,
                    CurrentConfig.ServerConfig.Password
                    );

                connection.Open();

                Databases dbs = Databases.GetDatabases(connection);
                string m = "Já existe uma base de dados com este nome no servidor.\r\n\r\n";
                m += "Tem certeza que deseja excluir esta base de dados e continuar com a instalação?\r\n\r\n\t\t";
                m += "ESTA AÇÃO NÃO PODERÁ SER DESFEITA. CERTIFIQUE-SE QUE TENHA UMA CÓPIA SE PRECISAR RETORNAR OS DADOS.";

                if(dbs.Contains(CurrentConfig.ServerConfig.Database) &&
                    MessageBox.AskYesNo(m) == System.Windows.Forms.DialogResult.No)
                    throw new Exception("A base de dados \"" + CurrentConfig.ServerConfig.Database + "\" não pode ser usada para esta instalação, pois já está sendo usada por outro processo.");

                try
                {
                    createDatabase = String.Format(@"SELECT pg_terminate_backend(pid)
                                                        FROM pg_stat_activity
                                                        WHERE pg_stat_activity.datname = '{0}'", CurrentConfig.ServerConfig.Database);
                    connection.ExecuteNonQuery(createDatabase);
                }
                catch
                {
                    createDatabase = String.Format(@"SELECT pg_terminate_backend(procpid)
                                                        FROM pg_stat_activity
                                                        WHERE pg_stat_activity.datname = '{0}'", CurrentConfig.ServerConfig.Database);
                    connection.ExecuteNonQuery(createDatabase);
                }

                createDatabase = String.Format(@"DROP DATABASE IF EXISTS {0};", CurrentConfig.ServerConfig.Database);
                connection.ExecuteNonQuery(createDatabase);

                createDatabase = String.Format(@"CREATE DATABASE {0}
                                                    WITH
                                                    ENCODING = 'LATIN1'
                                                    TABLESPACE = pg_default
                                                    LC_COLLATE = 'C'
                                                    LC_CTYPE = 'C'
                                                    TEMPLATE = template0
                                                    CONNECTION LIMIT = -1;",
                                  CurrentConfig.ServerConfig.Database);
                connection.ExecuteNonQuery(createDatabase);
            }

            return result;
        }
开发者ID:njmube,项目名称:openposbr,代码行数:60,代码来源:InstallPGSql.cs

示例6: _CreateTablesForType

 private void _CreateTablesForType(Type type, Connection conn)
 {
     List<Type> types = new List<Type>();
     types.Add(type);
     if (new List<Type>(type.GetInterfaces()).Contains(typeof(IClassView)))
     {
         ClassViewAttribute cva = conn.Pool[type];
         foreach (Type t in cva.Query.RequiredTypes)
         {
             if (!types.Contains(t))
                 types.Add(t);
             types = _RecurLoadTypesForTable(_pool.Mapping[t], types);
         }
     }
     else
         types = _RecurLoadTypesForTable(_pool.Mapping[type], types);
     for (int x = 1; x < types.Count; x++)
     {
         if (_createdTypes.Contains(types[x]))
         {
             types.RemoveAt(x);
             x--;
         }
     }
     List<ExtractedTableMap> tables;
     List<Trigger> triggers;
     List<Generator> generators;
     List<IdentityField> identities;
     List<View> views;
     List<StoredProcedure> procedures;
     ExtractExpectedStructure(ref types, out tables, out triggers, out generators, out identities, out views, out procedures, conn);
     List<string> createdTables = _UpdateStructure(tables, triggers, generators, identities, views, procedures,conn);
     foreach (Type t in types)
     {
         if (Utility.IsEnum(t))
         {
             if (createdTables.Contains(_pool.Enums[t]))
                 _pool.Enums.InsertEnumIntoTable(t, conn);
             else
                 _pool.Enums.LoadEnumsFromTable(t, conn);
         }
     }
     _createdTypes.AddRange(types);
     _UpdateAddiontalData(triggers, generators, identities, views, procedures);
     if (!_pool.DebugMode && (_translations.Count > 0))
     {
         foreach (Type t in types)
         {
             if (_translations.ContainsKey(t))
             {
                 foreach (EnumTranslationPair etp in _translations[t])
                 {
                     conn.ExecuteNonQuery(String.Format(
                         "UPDATE {0} SET {1} = '{3}' WHERE {1} = '{2}'",
                         new object[]{
                         _pool.Enums[t],
                         _pool.Translator.GetEnumValueFieldName(t,conn),
                         etp.OriginalName,
                         etp.NewName}
                     ));
                     conn.Close();
                 }
             }
             Dictionary<string, int> enumValuesMap = new Dictionary<string, int>();
             Dictionary<int, string> enumReverseValuesMap = new Dictionary<int, string>();
             List<string> enumNames = new List<string>(Enum.GetNames(t));
             List<int> deletes = new List<int>();
             conn.ExecuteQuery(String.Format("SELECT ID,{1} FROM {0}",
                 _pool.Enums[t],
                 _pool.Translator.GetEnumValueFieldName(t, conn)));
             while (conn.Read())
             {
                 if (enumNames.Contains(conn[1].ToString()))
                 {
                     enumValuesMap.Add(conn[1].ToString(), (int)conn[0]);
                     enumReverseValuesMap.Add((int)conn[0], conn[1].ToString());
                     enumNames.Remove(conn[1].ToString());
                 }
                 else
                     deletes.Add((int)conn[0]);
             }
             conn.Close();
             if (deletes.Count > 0)
             {
                 foreach (int i in deletes)
                 {
                     conn.ExecuteNonQuery(String.Format("DELETE FROM {0} WHERE ID = {1}",
                         _pool.Enums[t],
                         i));
                     conn.Close();
                 }
             }
             if (enumNames.Count > 0)
             {
                 foreach (string str in enumNames)
                 {
                     conn.ExecuteNonQuery(String.Format("INSERT INTO {0}({1}) VALUES('{2}')",
                         _pool.Enums[t],
                         _pool.Translator.GetEnumValueFieldName(t, conn),
                         str));
//.........这里部分代码省略.........
开发者ID:marquismark,项目名称:dbpro-orm,代码行数:101,代码来源:StructureUpdater.cs

示例7: WipeOutEnums

 internal void WipeOutEnums(Connection c)
 {
     foreach (Type t in _enumTableMaps.Keys)
         c.ExecuteNonQuery("DELETE FROM " + _enumTableMaps[t]);
 }
开发者ID:marquismark,项目名称:dbpro-orm,代码行数:5,代码来源:EnumsHandler.cs

示例8: _SyncMissingValues

 private Dictionary<string, int> _SyncMissingValues(Dictionary<string, int> vals, Type t, Connection conn)
 {
     t = (t.IsGenericType ? t.GetGenericArguments()[0] : t);
     string[] keys = new string[vals.Count];
     vals.Keys.CopyTo(keys, 0);
     foreach (string str in Enum.GetNames(t))
     {
         if (!vals.ContainsKey(str))
         {
             conn.ExecuteNonQuery(string.Format("INSERT INTO {0}({1}) VALUES({2});",new object[]{ 
                 _enumTableMaps[t],
                 _pool.Translator.GetEnumValueFieldName(t, conn),
                 conn.CreateParameterName("value")}),
             new System.Data.IDbDataParameter[]{
                         conn.Pool.CreateParameter(conn.CreateParameterName("id"),null,Org.Reddragonit.Dbpro.Structure.Attributes.FieldType.INTEGER,4),
                         conn.CreateParameter(conn.CreateParameterName("value"),str)
                     });
             conn.ExecuteQuery("SELECT ID FROM " + _enumTableMaps[t] + " WHERE " + _pool.Translator.GetEnumValueFieldName(t, conn) + " = " + conn.CreateParameterName("value"),
                 new IDbDataParameter[]{
                     conn.CreateParameter(conn.CreateParameterName("value"),str)
                 });
             conn.Read();
             vals.Add(str, conn.GetInt32(0));
             conn.Close();
         }
     }
     return vals;
 }
开发者ID:marquismark,项目名称:dbpro-orm,代码行数:28,代码来源:EnumsHandler.cs

示例9: InsertEnumIntoTable

 internal void InsertEnumIntoTable(Type t, Connection conn)
 {
     t = (t.IsGenericType ? t.GetGenericArguments()[0] : t);
     foreach (string str in Enum.GetNames(t))
     {
         conn.ExecuteNonQuery(string.Format("INSERT INTO {0}({1}) VALUES({2});",
                 _enumTableMaps[t],
                 _pool.Translator.GetEnumValueFieldName(t, conn),
                 conn.CreateParameterName("value")),
             new System.Data.IDbDataParameter[]{conn.CreateParameter(conn.CreateParameterName("value"),str)});
     }
     conn.Commit();
     LoadEnumsFromTable(t, conn);
 }
开发者ID:marquismark,项目名称:dbpro-orm,代码行数:14,代码来源:EnumsHandler.cs

示例10: InsertToDB

 internal void InsertToDB(Type t, int id, string value, Connection c)
 {
     t = (t.IsGenericType ? t.GetGenericArguments()[0] : t);
     c.ExecuteNonQuery("INSERT INTO " + _enumTableMaps[t] + " VALUES(" + c.CreateParameterName("id") + "," + c.CreateParameterName("value") + ");",
                     new System.Data.IDbDataParameter[]{
                         c.Pool.CreateParameter(c.CreateParameterName("id"),id),
                         c.Pool.CreateParameter(c.CreateParameterName("value"),value)
                     });
 }
开发者ID:marquismark,项目名称:dbpro-orm,代码行数:9,代码来源:EnumsHandler.cs


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