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


C# SqlClient.SqlConnection类代码示例

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


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

示例1: GetHandoverLogByHandoverLogId

        public static DataTable GetHandoverLogByHandoverLogId(int handoverLogId)
        {
            string connectionString = ConnectionStringFactory.GetNXJCConnectionString();
            DataSet ds = new DataSet();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = @"SELECT  WorkingTeamShiftLog.*,
                                                StaffInfo.Name AS ChargeManName, ProductLine.Name AS ProductLineName,
                                                WorkingTeam.Name AS WorkingTeamName
                                        FROM    WorkingTeam INNER JOIN
                                                StaffInfo INNER JOIN
                                                WorkingTeamShiftLog ON StaffInfo.ID = WorkingTeamShiftLog.ChargeManID INNER JOIN
                                                ProductLine ON WorkingTeamShiftLog.ProductLineID = ProductLine.ID ON
                                                WorkingTeam.ID = WorkingTeamShiftLog.WorkingTeamID
                                        WHERE   (WorkingTeamShiftLog.ID = @workingTeamShiftLogID)";

                command.Parameters.Add(new SqlParameter("workingTeamShiftLogID", handoverLogId));
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(ds);
            }

            return ds.Tables[0];
        }
开发者ID:nxjcproject,项目名称:nxjcslim,代码行数:25,代码来源:HandoverLogService.cs

示例2: Main

        public static void Main()
        {
            using (SqlConnection dbcon = new SqlConnection(ImageExtracter.ConnectionString))
            {
                dbcon.Open();

                SqlCommand command = new SqlCommand("SELECT Picture FROM Categories", dbcon);
                var reader = command.ExecuteReader();
                var counter = 0;

                while (reader.Read())
                {
                    byte[] imageByteArray = (byte[])reader["Picture"];

                    const int oleMetaPictStartPosition = 78;
                    var memoryStream =
                        new MemoryStream(imageByteArray, oleMetaPictStartPosition,
                            imageByteArray.Length - oleMetaPictStartPosition);

                    using (memoryStream)
                    {
                        using (var image = Image.FromStream(memoryStream, true, true))
                        {
                            image.Save("../../picture" + (++counter) + ".jpg");
                        }
                    }
                }
            }

            Console.WriteLine("Images exported successfully!");
            Console.WriteLine("See project folder for results!");
        }
开发者ID:zondario,项目名称:TelerikAcademy-Homeworks,代码行数:32,代码来源:ImageExtracter.cs

示例3: DataPortal_Insert

        protected override void DataPortal_Insert()
        {
            bool cancel = false;
            OnInserting(ref cancel);
            if (cancel) return;

            const string commandText = "INSERT INTO [dbo].[Category] ([CategoryId], [Name], [Descn]) VALUES (@p_CategoryId, @p_Name, @p_Descn)";
            using (var connection = new SqlConnection(ADOHelper.ConnectionString))
            {
                connection.Open();
                using(var command = new SqlCommand(commandText, connection))
                {
                    command.Parameters.AddWithValue("@p_CategoryId", this.CategoryId);
                command.Parameters.AddWithValue("@p_Name", ADOHelper.NullCheck(this.Name));
                command.Parameters.AddWithValue("@p_Descn", ADOHelper.NullCheck(this.Description));

                    //result: The number of rows changed, inserted, or deleted. -1 for select statements; 0 if no rows were affected, or the statement failed. 
                    int result = command.ExecuteNonQuery();
                    if (result == 0)
                        throw new DBConcurrencyException("The entity is out of date on the client. Please update the entity and try again. This could also be thrown if the sql statement failed to execute.");

                    LoadProperty(_originalCategoryIdProperty, this.CategoryId);
                }

                FieldManager.UpdateChildren(this, connection);
            }

            OnInserted();

        }
开发者ID:codesmithtools,项目名称:Framework-Samples,代码行数:30,代码来源:Category.DataAccess.cs

示例4: EnumerateClients

        public IEnumerable<UserInfoShort> EnumerateClients(string fio, string login, int pageNumber, int countPerPage)
        {
            using (var connection = new SqlConnection(_configurationService.DatabaseConnectionString))
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "sp_EnumerateClients";
                    command.Parameters.AddWithValue("@FIO", fio ?? (object)DBNull.Value).SqlDbType = SqlDbType.NVarChar;
                    command.Parameters.AddWithValue("@Login",
                        login != null ? login.ToLower() : (object)DBNull.Value).SqlDbType = SqlDbType.NVarChar;
                    command.Parameters.AddWithValue("@PageNumber", pageNumber).SqlDbType = SqlDbType.Int;
                    command.Parameters.AddWithValue("@CountPerPage", countPerPage).SqlDbType = SqlDbType.Int;
                    connection.Open();
                    using (var reader = command.ExecuteReader())
                    {
                        var lst = new List<UserInfoShort>();
                        while (reader.Read())
                        {
                            lst.Add(new UserInfoShort
                                {
                                    UserId = (Guid)reader["UserId"],
                                    CounOfCardAccounts = (int)reader["CounOfCardAccounts"],
                                    FIO = (string)reader["FIO"],
                                    Login = (string)reader["Login"],
                                    RegistrationDate = (DateTime)reader["RegistrationDate"]
                                });
                        }

                        return lst;
                    }
                }
            }
        }
开发者ID:khats,项目名称:Coffee,代码行数:34,代码来源:AdministratorRepository.cs

示例5: PH_BHTrans_Calc

        public static int PH_BHTrans_Calc(string strConnDB, string strYearWeek)
        {
            try
            {
                int rtn = 0;
                using (SqlConnection sqlConn = new SqlConnection(strConnDB))
                {
                    if (sqlConn.State == ConnectionState.Closed ) sqlConn.Open();
                    SqlCommand sqlComm = new SqlCommand("usp_BH_Transaction_Calc", sqlConn);
                    sqlComm.CommandText = "usp_BH_Transaction_Calc";
                    sqlComm.CommandType = CommandType.StoredProcedure;
                    sqlComm.CommandTimeout = 0;
                    sqlComm.Parameters.AddRange(new SqlParameter[] { new SqlParameter("@Tesco_Week", strYearWeek) });
                    rtn = sqlComm.ExecuteNonQuery();
                }
                    //int rtn =
                    //SqlTransaction sqlTran = new SqlConnection(strConnDB).BeginTransaction();

                    //SqlHelper.ExecuteNonQuery(strConnDB, CommandType.StoredProcedure, "usp_BH_Transaction_Calc"
                    //            , new SqlParameter[] {new SqlParameter("@Tesco_Week",strYearWeek)
                    //                                 });

                    return rtn;
            }
            catch (Exception ex)
            {
                throw new Exception("PH_BHTrans_Calc >> " + ex.Message);
            }
        }
开发者ID:parnupongk,项目名称:primary,代码行数:29,代码来源:PH_BHCalc.cs

示例6: GetTiposVenda

 private DataTable GetTiposVenda()
 {
     DataTable dataTable = new DataTable();
     this.con = new SqlConnection(Security.GetCnn());
     string selectCommandText = "";
     if (this._dev != "D")
     {
         selectCommandText = "select tipo_venta_id, descripcion, devolucion from Tipo_venta where devolucion='N'";
     }
     else
     {
         selectCommandText = "select tipo_venta_id, descripcion, devolucion from Tipo_venta where devolucion='S'";
     }
     if ((this.con != null) && (this.con.State == ConnectionState.Open))
     {
         this.con.Close();
     }
     this.con.Open();
     try
     {
         new SqlDataAdapter(selectCommandText, this.con).Fill(dataTable);
         this.con.Close();
     }
     catch (Exception)
     {
     }
     return dataTable;
 }
开发者ID:jcardeira,项目名称:saudefact,代码行数:28,代码来源:cTipoVenda.cs

示例7: FindProductBy

        private static ICollection<string> FindProductBy(string partOfName)
        {
            var names = new List<string>();
            string connectionString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=SSPI;";

            var dbCon = new SqlConnection(connectionString);

            dbCon.Open();
            using (dbCon)
            {
                SqlCommand command = new SqlCommand(
                    "SELECT p.ProductName FROM Products p WHERE p.ProductName LIKE @Search", dbCon);

                command.Parameters.AddWithValue("@Search", "%" + partOfName + "%");

                SqlDataReader reader = command.ExecuteReader();

                Console.WriteLine("\nProductNams that contains ({0}):\n", partOfName);
                using (reader)
                {
                    string categoryName = string.Empty;
                    string currentCategoryName = string.Empty;
                    while (reader.Read())
                    {
                        string productName = (string)reader["ProductName"];

                        names.Add(productName);
                    }
                }
            }

            return names;
        }
开发者ID:razsilev,项目名称:TelerikAcademy_Homework,代码行数:33,代码来源:Program.cs

示例8: GetOne

        public DataSet GetOne(string empresaid, tb_tipimpto BE)
        {
            using (SqlConnection cnx = new SqlConnection(conex.empConexion(empresaid)))
            {
                using (SqlCommand cmd = new SqlCommand("gspTbTipimpto_SELECT", cnx))
                {
                    DataSet ds = new DataSet();

                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@tipimptoid", SqlDbType.Char, 1).Value = BE.tipimptoid;
                    }

                    try
                    {
                        cnx.Open();
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            da.Fill(ds);
                        }
                        return ds;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
            }
        }
开发者ID:njmube,项目名称:ErpBapSoftNet_Producion,代码行数:29,代码来源:tb_tipimptoDA.cs

示例9: GetAllBootcampTechnologies

 public List<BootcampTechnology> GetAllBootcampTechnologies()
 {
     using (SqlConnection connection = new SqlConnection(Settings.GetConnectionString()))
     {
         return connection.Query<BootcampTechnology>("BootcampTechnologyGetAll", commandType: CommandType.StoredProcedure).ToList();
     }
 }
开发者ID:clabanow,项目名称:FutureCodr,代码行数:7,代码来源:BootcampTechnologyRepositorySql.cs

示例10: repositoryItemButtonEditSave_ButtonClick

 private void repositoryItemButtonEditSave_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
 {
     if (MessageBox.Show("هل انت متأكد؟", "تحزيــــر", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
         return;
     DataRow Row = (DataRow)gridViewMain.GetFocusedDataRow();
     SqlConnection con = new SqlConnection(MyCL.SqlConStr);
     SqlCommand cmd = new SqlCommand("", con);
     try
     {
         if (Row["knowID"].ToString() == string.Empty)// Is Unsaved Row?
         {
             string NewID = MyCL.GetNewID("CDknow", "knowID");
             cmd.CommandText = string.Format(@"Insert Into CDknow (knowID, know) VALUES ({0}, '{1}')",
             NewID, Row["know"]);
         }
         else
         {
             cmd.CommandText = string.Format(@"Update CDknow Set know = '{0}' Where knowID = {1}",
             Row["know"], Row["knowID"]);
         }
         con.Open();
         cmd.ExecuteNonQuery();
         MyCL.ShowMsg("تم الحفظ", false, this);
     }
     catch (SqlException ex)
     {
         MyCL.ShowMsg(MyCL.CheckExp(ex), true, this);
     }
     con.Close();
     LoadData();
 }
开发者ID:EgyFalseX-EESoft-WinForm,项目名称:Training-Center,代码行数:31,代码来源:CDknowFrm.cs

示例11: repositoryItemButtonEditDelete_ButtonClick

 private void repositoryItemButtonEditDelete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
 {
     if (MessageBox.Show("هل انت متأكد؟", "تحزيــــر", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
         return;
     DataRow Row = (DataRow)gridViewMain.GetFocusedDataRow();
     if (Row["knowID"].ToString() == string.Empty)// Is Unsaved Row?
     {
         LoadData();
         return;
     }
     SqlConnection con = new SqlConnection(MyCL.SqlConStr);
     SqlCommand cmd = new SqlCommand("", con);
     try
     {
         cmd.CommandText = @"Delete From CDknow Where knowID = " + Row["knowID"];
         con.Open();
         cmd.ExecuteNonQuery();
         MyCL.ShowMsg("تم الحذف", false, this);
     }
     catch (SqlException ex)
     {
         MyCL.ShowMsg(MyCL.CheckExp(ex), true, this);
     }
     con.Close();
     LoadData();
 }
开发者ID:EgyFalseX-EESoft-WinForm,项目名称:Training-Center,代码行数:26,代码来源:CDknowFrm.cs

示例12: Main

        public static void Main()
        {
            var connection = new SqlConnection(connectionString: "Server=(local); Database=Northwind; Integrated Security=true;");
            connection.Open();
            var command = new SqlCommand(cmdText: "select c.CategoryName, p.ProductName from Products p inner join Categories c on c.CategoryId = p.CategoryId;", connection: connection);

            var categoriesAndProducts = new Dictionary<string, List<string>>();
            var reader = command.ExecuteReader();
            while (reader.Read())
            {
                var category = (string)reader["CategoryName"];
                var product = (string)reader["ProductName"];
                if(categoriesAndProducts.ContainsKey(category))
                {
                    categoriesAndProducts[category].Add(product);
                }
                else
                {
                    categoriesAndProducts.Add(category, new List<string>());
                }
            }

            connection.Close();

            foreach (var kvp in categoriesAndProducts)
            {
                Console.WriteLine(new string(c: '=', count: 20) + "\n" + kvp.Key + "\n" + new string(c: '=', count: 20));

                foreach (var product in kvp.Value)
                {
                    Console.WriteLine("-- " + product);
                }
            }
        }
开发者ID:vassildinev,项目名称:Databases,代码行数:34,代码来源:EntryPoint.cs

示例13: load_price

        protected void load_price()
        {
            string price_name = null;
            string article = null;
            price_name = Request.QueryString["price_name"];
            article = Request.QueryString["article"];

            if (article != null)
            {
                if (price_name != null)
                {

                    SqlConnection con = new SqlConnection(str);
                    string sql = "SELECT id, article, ROUND([price]*(SELECT course FROM Course_USD WHERE id = 1),2) AS [price] FROM " + price_name + " WHERE article=" + article + ";";
                    SqlDataAdapter da = new SqlDataAdapter(sql, con);
                    DataSet ds = new DataSet();
                    da.Fill(ds, price_name);
                    DataRow dr;
                    dr = ds.Tables[price_name].Rows[0];

                    //Заполняем стоимость товара:
                    lblprice.Text = dr["price"].ToString();
                }
                else {Response.Redirect("Error.aspx");}

            }
            else {Response.Redirect("Error.aspx"); }
        }
开发者ID:sgkMoscow,项目名称:vorsinstrument,代码行数:28,代码来源:Zubilo_po_betonu_ploskoe_40x250mm_SDS_plus_Optim.aspx.cs

示例14: Ilceler

 public static DataTable Ilceler(int id)
 {
     try
     {
         using (baglan = new SqlConnection(ConnectionString))
         {
             baglan.Open();
             using (komutver = new SqlCommand())
             {
                 komutver.Connection = baglan;
                 komutver.CommandText = "ilce_Listele";
                 komutver.Parameters.Add("@ilceId", SqlDbType.Int);
                 komutver.Parameters["@ilceId"].Value = Convert.ToInt32(id);
                 komutver.CommandType = CommandType.StoredProcedure;
                 adp = new SqlDataAdapter(komutver);
                 dt = new DataTable();
                 adp.Fill(dt);
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
     return dt;
 }
开发者ID:ahmet-esmer,项目名称:asp.net-web-form-e-commerce,代码行数:26,代码来源:SehirDB.cs

示例15: Sehirler

        public static DataTable Sehirler()
        {
            try
            {
                using (baglan = new SqlConnection(ConnectionString))
                {
                    baglan.Open();
                    using (komutver = new SqlCommand())
                    {
                        komutver.Connection = baglan;
                        komutver.CommandText = "sehir_Listele";
                        komutver.CommandType = CommandType.StoredProcedure;
                        adp = new SqlDataAdapter(komutver);
                        dt = new DataTable();
                        adp.Fill(dt);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return dt;
        }
开发者ID:ahmet-esmer,项目名称:asp.net-web-form-e-commerce,代码行数:25,代码来源:SehirDB.cs


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