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


C# System.Data.SqlClient.SqlConnection.Open方法代码示例

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


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

示例1: AddNewVirtualDealer

        /// <summary>
        /// 
        /// </summary>
        /// <param name="objVirtualDealer"></param>
        /// <returns></returns>
        internal string AddNewVirtualDealer(Business.VirtualDealer objVirtualDealer)
        {
            string result = "-1";
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(DBConnection.DBConnection.Connection);
            System.Data.SqlClient.SqlTransaction trans = null;
            DSTableAdapters.VirtualDealerTableAdapter virtualDealerAdap = new DSTableAdapters.VirtualDealerTableAdapter();
            DSTableAdapters.VirtualDealerConfigTableAdapter dealerConfigAdap = new DSTableAdapters.VirtualDealerConfigTableAdapter();
            DSTableAdapters.IVirtualDealerTableAdapter iVirtualDealerAdap = new DSTableAdapters.IVirtualDealerTableAdapter();
            try
            {
                conn.Open();
                trans = conn.BeginTransaction();

                virtualDealerAdap.Connection = conn;
                virtualDealerAdap.Transaction = trans;
                int id = int.Parse(virtualDealerAdap.AddNewVirtualDealer(objVirtualDealer.Name, "").ToString());
                result = id.ToString();
                if (id == -1)
                {
                    throw new Exception("Data error");
                }

                dealerConfigAdap.Connection = conn;
                dealerConfigAdap.Transaction = trans;
                DateTime DateValue = DateTime.Parse("1753-01-01 00:00:00.000");
                dealerConfigAdap.Insert(null, "Profit max pip", id, "VD01", -1, "NaN", objVirtualDealer.ProfitMaxPip.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Loss max pip", id, "VD02", -1, "NaN", objVirtualDealer.LossMaxPip.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Min volume", id, "VD03", -1, "NaN", objVirtualDealer.StartVolume.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Max volume", id, "VD04", -1, "NaN", objVirtualDealer.EndVolume.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Delay", id, "VD05", -1, "NaN", objVirtualDealer.Delay.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Additional pip", id, "VD06", -1, "NaN", objVirtualDealer.AdditionalPip.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Mode", id, "VD07", -1, "NaN", objVirtualDealer.Mode.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "IsEnable", id, "VD08", objVirtualDealer.IsEnable ? 1 : 0, "NaN", "NaN", DateValue);
                dealerConfigAdap.Insert(null, "IsLimitAuto", id, "VD09", objVirtualDealer.IsLimitAuto ? 1 : 0, "NaN", "NaN", DateValue);
                dealerConfigAdap.Insert(null, "IsStopAuto", id, "VD10", objVirtualDealer.IsStopAuto ? 1 : 0, "NaN", "NaN", DateValue);
                dealerConfigAdap.Insert(null, "IsStopSlippage", id, "VD11", objVirtualDealer.IsStopSlippage ? 1 : 0, "NaN", "NaN", DateValue);
                dealerConfigAdap.Insert(null, "GroupCondition", id, "VD12", -1, objVirtualDealer.GroupCondition, "NaN", DateValue);
                dealerConfigAdap.Insert(null, "SymbolCodition", id, "VD13", -1, objVirtualDealer.SymbolCondition, "NaN", DateValue);
                iVirtualDealerAdap.Connection = conn;
                iVirtualDealerAdap.Transaction = trans;
                for (int i = 0; i < objVirtualDealer.IVirtualDealer.Count; i++)
                {
                    iVirtualDealerAdap.Insert(objVirtualDealer.IVirtualDealer[i].InvestorGroupID, objVirtualDealer.IVirtualDealer[i].SymbolID, id);
                }
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                return "Data error";
            }
            finally
            {
                virtualDealerAdap.Connection.Close();
                dealerConfigAdap.Connection.Close();
                iVirtualDealerAdap.Connection.Close();
                conn.Close();
            }
            return result;
        }
开发者ID:ngthanhducit,项目名称:TradingServer1502,代码行数:65,代码来源:DBWVirtualDealer.cs

示例2: CreateDatabase

        public static string CreateDatabase(Models.Lodge model, string appDataMapPath)
        {
            string success = "no";
            try
            {
                model.DatabaseName = model.LodgeName.Replace(" ", "").Replace(".", "");
                using (var connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["MasonMaster"].ConnectionString))
                {
                    connection.Open();
                    using (var command = connection.CreateCommand())
                    {
                        // SQLEXPRESS
                        //command.CommandText = String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", model.DatabaseName, filename);
                        //command.ExecuteNonQuery();
                        //command.CommandText = String.Format("EXEC sp_detach_db '{0}', 'true'", model.DatabaseName);
                        //command.ExecuteNonQuery();
                        //CREATE DATABASE SampleLodge ON (
                        // NAME = SampleLodge,
                        // FILENAME = 'C:\git\LodgeSecretary\LodgeSecretary\App_Data\SampleLodge.mdf')
                        // LOG ON
                        //( name = SampleLodge_Log,
                        //  FILENAME = 'C:\git\LodgeSecretary\LodgeSecretary\App_Data\SampleLodge_Log.ldf')

                        // Full SQL Server
                        command.CommandText = string.Format("use master CREATE DATABASE {0} ON (NAME = {0}, FILENAME = '{1}{0}.mdf') " +
                            "LOG ON ( name = {0}_Log, FILENAME = '{1}{0}_Log.ldf')", model.DatabaseName, appDataMapPath);
                        command.ExecuteNonQuery();
                        success = "ok";
                    }
                }
            }
            catch (Exception ex) { success = ex.Message; }
            return success;
        }
开发者ID:CurtisRhodes,项目名称:LodgeSecretary,代码行数:34,代码来源:MasonMasterData.cs

示例3: test_connection_btn_Click

 private void test_connection_btn_Click(object sender, EventArgs e)
 {
     var bldr = new System.Data.SqlClient.SqlConnectionStringBuilder();
     bldr.DataSource = serverTextBox.Text;
     bldr.InitialCatalog = dbNameTextBox.Text;
     bldr.IntegratedSecurity = windows_auth_cb.Checked;
     if (sql_auth_cb.Checked)
     {
         bldr.UserID = username_tb.Text;
         bldr.Password = password_tb.Text;
     }
     bldr.ConnectTimeout = 5;
     var conn = new System.Data.SqlClient.SqlConnection(bldr.ConnectionString);
     var success = false;
     try
     {
         conn.Open();
         var cmd = conn.CreateCommand();
         cmd.CommandText = "select 1";
         cmd.ExecuteScalar();
         success = true;
     }
     catch (Exception ex)
     {
         MessageBox.Show("Test connection failed because of an error in initializing provider. " + ex.Message,
                         "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     if (success)
     {
         MessageBox.Show("Test connection succeeded.", "CutOptima",
                         MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
开发者ID:boussaffawalid,项目名称:CutOptima,代码行数:33,代码来源:ExistingDatabaseForm.cs

示例4: xxGetMemberDetail

 public static Accomplishment xxGetMemberDetail(string memberDetailId, string connString)
 {
     var memberDetail = new Models.Accomplishment();
     try
     {
         using (var connection = new System.Data.SqlClient.SqlConnection(connString))
         {
             connection.Open();
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = string.Format("Select * from lodge.MemberDetail where MemberDetailId ='{0}'", memberDetailId);
                 var reader = command.ExecuteReader();
                 if (reader.HasRows)
                 {
                     reader.Read();
                     {
                         memberDetail.AccomplishmentId = memberDetailId;
                         memberDetail.MasonId = (int)reader["MasonId"];
                         memberDetail.AccomplishmentType = reader["MemberDetailTypeRef"].ToString();
                         memberDetail.ShortTitle = reader["ShortTitle"].ToString();
                         memberDetail.Location = reader["Location"].ToString();
                         memberDetail.StartDate = reader["StartDate"].ToString();
                         memberDetail.EndDate = reader["EndDate"].ToString();
                         memberDetail.Comments = reader["Comments"].ToString();
                     }
                 }
             }
         }
     }
     catch (Exception ex) { memberDetail.Comments = ex.Message; }
     return memberDetail;
 }
开发者ID:CurtisRhodes,项目名称:LodgeSecretary,代码行数:32,代码来源:MemberDataSql.cs

示例5: GetData

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        internal List<Business.LastBalance> GetData()
        {
            List<Business.LastBalance> result = new List<Business.LastBalance>();

            DSTableAdapters.LastAccountTableAdapter adap = new DSTableAdapters.LastAccountTableAdapter();
            DS.LastAccountDataTable tbLastBalance = new DS.LastAccountDataTable();
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(DBConnection.DBConnection.Connection);

            try
            {
                conn.Open();
                adap.Connection = conn;
                tbLastBalance = adap.GetData();

                result = this.MapLastBalance(tbLastBalance);
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                adap.Connection.Close();
                conn.Close();
            }

            return result;
        }
开发者ID:ngthanhducit,项目名称:TradingServer1502,代码行数:32,代码来源:DBWLastBalance.cs

示例6: AddGroup

       public static bool AddGroup(string intranetGroupName)
        {
            try
            {
                int groupID = 0;
                //Получаем идентификатор группы
                using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString))
                {
                    using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("INSERT INTO groups(group_id,group_name) VALUES((SELECT MIN(group_id)-1 FROM groups WHERE id>-1000), @name)", conn))
                    {
                        try
                        {
                            conn.Open();
                            cmd.Parameters.AddWithValue("@name", intranetGroupName);
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Core.Logging.WriteEntry("Ошибка добавления группы.", ex, 1);
                return false;
            }
        }
开发者ID:EkzoMan,项目名称:Ekzo.Security,代码行数:30,代码来源:AuthLib.Helpers.RoleProviderHelper.cs

示例7: UpdateInvestorProfile

        /// <summary>
        /// 
        /// </summary>
        /// <param name="objInvestor"></param>
        /// <returns></returns>
        internal bool UpdateInvestorProfile(Business.Investor objInvestor)
        {
            bool Result = false;
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(DBConnection.DBConnection.Connection);
            DSTableAdapters.InvestorProfileTableAdapter adap = new DSTableAdapters.InvestorProfileTableAdapter();

            try
            {
                conn.Open();
                adap.Connection = conn;
                int ResultUpdate = adap.UpdateInvestorProfile(objInvestor.InvestorID, objInvestor.Address, objInvestor.Phone, objInvestor.City, objInvestor.Country, objInvestor.Email,
                    objInvestor.ZipCode, objInvestor.InvestorComment, objInvestor.State, objInvestor.NickName, objInvestor.IDPassport, objInvestor.InvestorProfileID);

                if (ResultUpdate > 0)
                    Result = true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                adap.Connection.Close();
                conn.Close();
            }

            return Result;
        }
开发者ID:ngthanhducit,项目名称:TradingServer1502,代码行数:33,代码来源:DBWInvestorProfile.cs

示例8: CbBackups_DropDown_1

 private void CbBackups_DropDown_1(object sender, EventArgs e)
 {
     using (var connection = new System.Data.SqlClient.SqlConnection(string.Format("Server={0};Database={1};Trusted_Connection=True;", TxtLocalBkp.Text, TxtDataBase.Text)))
     {
         connection.Open();
         using (var command = new System.Data.SqlClient.SqlCommand(
             "SELECT physical_device_name FROM msdb.dbo.backupmediafamily " +
             "INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id " +
             "WHERE (msdb.dbo.backupset.database_name LIKE @DatabaseName)", connection))
         {
             command.Parameters.AddWithValue("DatabaseName", TxtDataBase.Text);
             using (var reader = command.ExecuteReader())
             {
                 var table = new DataTable();
                 table.Load(reader);
                 table.Columns.Add("FriendlyName");
                 foreach (DataRow row in table.Rows)
                 {
                     row["FriendlyName"] = System.IO.Path.GetFileName(row["physical_device_name"].ToString());
                 }
                 if (CbBackups.DataSource != null && CbBackups.DataSource is DataTable)
                 {
                     var oldTable = ((DataTable)CbBackups.DataSource);
                     CbBackups.DataSource = null;
                     oldTable.Dispose();
                 }
                 CbBackups.DataSource = table;
                 CbBackups.DisplayMember = "FriendlyName";
                 CbBackups.ValueMember = "physical_device_name";
             }
         }
     }
 }
开发者ID:mrsalustiano,项目名称:VS_C,代码行数:33,代码来源:FrmBackupBancoDeDados.cs

示例9: AddStatement

        /// <summary>
        /// 
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        internal int AddStatement(List<Business.Statement> values)
        {
            int result = -1;
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(DBConnection.DBConnection.Connection);
            DSTableAdapters.StatementTableAdapter adap = new DSTableAdapters.StatementTableAdapter();

            try
            {
                if (values != null && values.Count > 0)
                {
                    conn.Open();
                    adap.Connection = conn;

                    int count = values.Count;
                    for (int i = 0; i < count; i++)
                    {
                        result = int.Parse(adap.AddNewStatement(values[i].InvestorCode, values[i].Content, values[i].TimeStatement,
                            values[i].Email, values[i].StatementType).ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                return -1;
            }
            finally
            {
                adap.Connection.Close();
                conn.Close();
            }

            return result;
        }
开发者ID:ngthanhducit,项目名称:TradingServer1502,代码行数:38,代码来源:DBWStatement.cs

示例10: DeleteIVirtualDealer

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iVirtualDealerID"></param>
        /// <returns></returns>
        internal bool DeleteIVirtualDealer(int iVirtualDealerID)
        {
            bool result = false;
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(DBConnection.DBConnection.Connection);
            DSTableAdapters.IVirtualDealerTableAdapter adap = new DSTableAdapters.IVirtualDealerTableAdapter();

            try
            {
                conn.Open();
                adap.Connection = conn;
                int resultDelete = adap.DeleteIVirtualDealer(iVirtualDealerID);
                if (resultDelete > 0)
                    result = true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                adap.Connection.Close();
                conn.Close();
            }

            return result;
        }
开发者ID:ngthanhducit,项目名称:TradingServer1502,代码行数:31,代码来源:DBWIVirtualDealer.cs

示例11: InitClass

 private void InitClass(int id, int groupID)
 {
     this.RoleID = id;
     this.GroupID = groupID;
     using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Configuration.ConnectionStringName].ConnectionString))
     {
         using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Authorization_RoleToControlGroup WHERE [email protected] AND [email protected]", conn))
         {
             try
             {
                 conn.Open();
                 cmd.Parameters.AddWithValue("@role", id);
                 cmd.Parameters.AddWithValue("@group", groupID);
                 System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
                 while (reader.Read())
                     this.id = reader.GetInt32(0);
             }
             catch (Exception ex)
             {
                 if (Configuration.s_log != null)
                     Configuration.s_log.Error("[Ошибка модуля авторизации] [Инициализация класса роли группы элементов управления] ", ex);
             }
         }
     }
 }
开发者ID:EkzoMan,项目名称:Ekzo.Security,代码行数:25,代码来源:Ekzo.Web.Security.Utilization.Authorization.ControlsGroupRole.cs

示例12: btnBackup_Click

        private void btnBackup_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string path = String.Format("{0}\\{1}PharmaInventory{2:MMMddyyyy}.bak", folderBrowserDialog1.SelectedPath, GeneralInfo.Current.HospitalName, DateTimeHelper.ServerDateTime);

                    string connectionString = readApp.GetValue("dbConnection", typeof(string)).ToString();

                    System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);
                    System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand();

                    if (!(conn.State == ConnectionState.Open))
                        conn.Open();
                    string dbName = conn.Database;
                    com.CommandText = "BACKUP DATABASE [" + dbName + "] TO  DISK = N'" + path + "' WITH NOFORMAT, NOINIT,  NAME = N'PharmaInventory" + DateTimeHelper.ServerDateTime.ToString("MMMddyyyy") + "-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
                    com.Connection = conn;
                    com.ExecuteNonQuery();

                    GeneralInfo.Current.LastBackUp = DateTimeHelper.ServerDateTime;
                    GeneralInfo.Current.Save();
                    MessageBox.Show(@"Backup completed to " + path + @"!", @"Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch
                {
                    MessageBox.Show(@"Backup has failed! Please Try Again.",@"Try Again",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
        }
开发者ID:USAID-DELIVER-PROJECT,项目名称:ethiopia-hcmis-warehouse,代码行数:30,代码来源:DatabaseActions.cs

示例13: GetKeysInternal

        private static List<KeyInfo> GetKeysInternal(Config config, String connectionString, String keyType)
        {
            Dictionary<String, KeyInfo> keys = new Dictionary<string, KeyInfo>();

            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString))
            {
                conn.Open();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(String.Format("select s.name, o.name, i.name from sys.objects o join sys.indexes i on i.object_id = o.object_id join sys.schemas s on s.schema_id = o.schema_id where i.type_desc = '{0}' and i.is_primary_key = 1 and o.type = 'U' order by 1", keyType), conn);
                using (System.Data.SqlClient.SqlDataReader r = cmd.ExecuteReader())
                {
                    while (r.Read())
                    {
                        String schemaName = r[0].ToString();
                        String tableName = r[1].ToString();
                        String keyName = r[2].ToString();
                        keys.Add((schemaName + tableName).ToLower(), new KeyInfo() { Name = keyName, SchemaName = schemaName, TableName = tableName });
                    }
                }
            }

            Dictionary<String, List<Entity>> schemas = config.EntitiesBySchema;
            List<KeyInfo> result = new List<KeyInfo>();
            foreach (KeyValuePair<String, KeyInfo> kvp in keys)
            {
                if (schemas.ContainsKey(kvp.Value.SchemaName))
                    result.Add(kvp.Value);
            }

            return result;
        }
开发者ID:Fedorm,项目名称:core-master,代码行数:30,代码来源:KeysPatcher.cs

示例14: SystemRole

        public SystemRole(int baseID, int actionGroup = 0)
        {

            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[Ekzo.Web.Configuration.UsersStringName].ConnectionString))
            {
                using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT group_name FROM groups WHERE [email protected]", conn))
                {
                    try
                    {
                        conn.Open();
                        cmd.Parameters.AddWithValue("@id", baseID);
                        System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                            this.Role = reader.GetString(0);
                        this.baseID = baseID;
                        this.ActionGroup = actionGroup;
                    }
                    catch (Exception ex)
                    {
                        if (Configuration.s_log != null)
                            Configuration.s_log.Error("[Ошибка модуля авторизации] [Инициализация роли из справочника] ", ex);
                    }
                }
            }
        }
开发者ID:EkzoMan,项目名称:Ekzo.Security,代码行数:25,代码来源:Ekzo.Web.Security.Utilization.Authorization.SystemRole.cs

示例15: Create

        public string Create(EventModel eventEntity)
        {
            try
            {
                using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
                {
                    sqlConnection.Open();

                    string sqlQuery = "INSERT INTO Event(_EventType_key,EventID,EventName,ProjectedDate,ActualDate,_Workgroup_key,CreatedBy,DateCreated,ModifiedBy,DateModified) VALUES (@_EventType_key,@EventID,@EventName,@ProjectedDate,@ActualDate,@_Workgroup_key,@CreatedBy,@DateCreated,@ModifiedBy,@DateModified)";
                    sqlConnection.Execute(sqlQuery,
                                          new
                                          {
                                              eventEntity._EventType_key,
                                              eventEntity.EventID,
                                              eventEntity.EventName,
                                              eventEntity.ProjectedDate,
                                              eventEntity.ActualDate,
                                              eventEntity._Workgroup_key,
                                              eventEntity.CreatedBy,
                                              eventEntity.DateCreated,
                                              eventEntity.ModifiedBy,
                                              eventEntity.DateModified
                                          });

                    sqlConnection.Close();

                }
                return "Created";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
开发者ID:spikemcfarland,项目名称:CLIMB,代码行数:34,代码来源:EventDB.cs


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