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


C# SqlClient.SqlCommand类代码示例

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


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

示例1: Delete

 public bool Delete(string empresaid, tb_co_tabla01_mediopago BE)
 {
     using (SqlConnection cnx = new SqlConnection(conex.empConexion(empresaid)))
     {
         using (SqlCommand cmd = new SqlCommand("gspTbCoTabla01Mediopago_DELETE", cnx))
         {
             {
                 cmd.CommandTimeout = 0;
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.Add("@codigoid", SqlDbType.Char, 3).Value = BE.codigoid;
             }
             try
             {
                 cnx.Open();
                 if (cmd.ExecuteNonQuery() > 0)
                 {
                     return true;
                 }
                 else
                 {
                     return false;
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }
     }
 }
开发者ID:njmube,项目名称:ErpBapSoftNet_Producion,代码行数:30,代码来源:tb_co_tabla01_mediopagoDA.cs

示例2: GetUsuarioSinPass

        public static Usuario GetUsuarioSinPass(String puser)
        {
            Usuario usuario = null;
            var sqlQuery = "SELECT  (c.nombre +' '+ c.apellidos) As nombre_completo, u.id_usuario, u.nombre_usuario, u.id_empleado,  u.id_rol, u.pregunta_seguridad, u.respuesta_seguridad FROM Usuarios u  JOIN Empleados e On u.id_empleado = e.id_empleado JOIN Candidatos c On e.id_candidato = c.id_candidato WHERE u.nombre_usuario  = @puser and u.esta_oculto=0 ";
            SqlCommand cmd = new SqlCommand();
            cmd.Parameters.AddWithValue("@puser", puser);

            var ds = DBAccess.ExecuteSQLWithDS(cmd, sqlQuery);
            if (ds.Tables[0].Rows.Count > 0)
            {
                var dr = ds.Tables[0].Rows[0];
                usuario = new Usuario
                {
                    Id = Convert.ToInt32(dr["id_usuario"]),
                    NombreUsuario = dr["nombre_usuario"].ToString(),
                    IdEmpleado = Convert.ToInt32(dr["id_empleado"]),
                    IdRol = Convert.ToInt32(dr["id_rol"].ToString()),
                    PreguntaSeguridad = dr["pregunta_seguridad"].ToString(),
                    RespuestaSeguridad = dr["respuesta_seguridad"].ToString(),
                    NombreCompleto = dr["nombre_completo"].ToString()
                };
            }

            return usuario;
        }
开发者ID:pablobar23,项目名称:RRHH,代码行数:25,代码来源:Seguridad.cs

示例3: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
            string requestFromPost = reader.ReadToEnd();

            //loop through
               // string formValue;

            string speed;
            string initialLocation;
            string finalLocation;
            string IMEI;

            if (!string.IsNullOrEmpty(Request.Form["txtSpeed"]))
            {
                //formValue = Request.Form["txtSpeed"];
                //formValue = Request.Form["txtImei"];
                speed = Request.Form["Speed"];
                initialLocation = Request.Form["initialLocation"];
                finalLocation = Request.Form["finalLocation"];
                IMEI = Request.Form["IMEI"];

                string s = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
                SqlConnection cn = new SqlConnection(s);
                cn.Open();
                SqlCommand cmd = new SqlCommand("insert into DataHistory(Speed, initialLocation, finalLocation, IMEI)values('" + speed + "','" + initialLocation + "','" + finalLocation + "','" + IMEI + "')", cn);
                cmd.ExecuteNonQuery();

            }
        }
开发者ID:niviaqua,项目名称:ParentGuardWebApp,代码行数:30,代码来源:DrivingData.aspx.cs

示例4: GetMessageByUser

        public RootObjectOut GetMessageByUser(UserIn jm)
        {
            RootObjectOut output = new RootObjectOut();
            String jsonString = "";
            try
            {
                String strConnection = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
                SqlConnection Connection = new SqlConnection(strConnection);
                String strSQL = string.Format("SELECT message FROM messages WHERE msgTo = '{0}' AND [msgID] = (SELECT MAX(msgID) FROM messages WHERE msgTo='{1}')", jm.user.ToString(),jm.user.ToString());
                SqlCommand Command = new SqlCommand(strSQL, Connection);
                Connection.Open();
                SqlDataReader Dr;
                Dr = Command.ExecuteReader();
                if (Dr.HasRows)
                {
                    if (Dr.Read())
                    {
                        jsonString = Dr.GetValue(0).ToString();
                    }
                }
                Dr.Close();
                Connection.Close();
            }
            catch (Exception ex)
            {
                output.errorMessage = ex.Message;
            }
            finally
            {
            }
            JavaScriptSerializer ser = new JavaScriptSerializer();
            output = ser.Deserialize<RootObjectOut>(jsonString);

            return output;
        }
开发者ID:kincade71,项目名称:is670,代码行数:35,代码来源:Get.cs

示例5: Main

        static void Main(string[] args)
        {
            Console.Write("Enter some text to search for it in the Products: ");
            var searchedProduct = Console.ReadLine();

            SqlConnection dbCon = new SqlConnection("Server=localhost; " +
                "Database=NORTHWND; Integrated Security=true");
            dbCon.Open();
            using (dbCon)
            {
                SqlCommand cmd = new SqlCommand(
                    "SELECT ProductName FROM Products " +
                    "WHERE CHARINDEX (@searchedProduct, ProductName)>0", dbCon);

                cmd.Parameters.AddWithValue("@searchedProduct", searchedProduct);

                SqlDataReader reader = cmd.ExecuteReader();
                using (reader)
                {
                    while (reader.Read())
                    {
                        string productName = (string)reader["ProductName"];
                        Console.WriteLine(productName);
                    }
                }
            }
        }
开发者ID:niki-funky,项目名称:Telerik_Academy,代码行数:27,代码来源:Program.cs

示例6: 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

示例7: 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

示例8: 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

示例9: FindUserEmailID

 public bool FindUserEmailID(int userEmailID)
 {
     string sql = string.Format("SELECT * FROM UserEmails WHERE UserEmailID = '{0}' ", userEmailID);
     using(Connection cn = new Connection())
     {
         using (SqlCommand cmd = new SqlCommand())
         {
             try
             {
                 cmd.Connection = cn.SqlConnection;
                 cmd.CommandText = sql;
                 int recordsAffected = cmd.ExecuteNonQuery();
                 SqlDataReader reader = cmd.ExecuteReader();
                 if (reader.HasRows)
                 {
                     while (reader.Read())
                     {
                         //UserID = (int)reader["UserID"];
                         //loginName = reader["LoginName"].ToString();
                     }
                     return true;
                 }
                 else
                     return false;
             }
             catch (Exception ex)
             {
                 System.Diagnostics.Debug.WriteLine(ex.Message);
                 return false;
             }
         }
     }
     //return true;
 }
开发者ID:MagnusTiberius,项目名称:GigaBoom,代码行数:34,代码来源:UserEmail.cs

示例10: 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

示例11: GetAll

 public DataSet GetAll(string empresaid, tb_co_tabla01_mediopago BE)
 {
     using (SqlConnection cnx = new SqlConnection(conex.empConexion(empresaid)))
     {
         using (SqlCommand cmd = new SqlCommand("gspTbCoTabla01Mediopago_SEARCH", cnx))
         {
             DataSet ds = new DataSet();
             {
                 cmd.CommandTimeout = 0;
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.Add("@codigoid", SqlDbType.Char, 3).Value = BE.codigoid;
                 cmd.Parameters.Add("@descripcion", SqlDbType.VarChar, 100).Value = BE.descripcion;
                 cmd.Parameters.Add("@sigla", SqlDbType.Char, 3).Value = BE.sigla;
                 cmd.Parameters.Add("@usuar", SqlDbType.Char, 15).Value = BE.usuar;
             }
             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,代码行数:31,代码来源:tb_co_tabla01_mediopagoDA.cs

示例12: GetDBBackup

        public void GetDBBackup(string backupDBName, string backupPath)
        {
            try
            {
                DataBaseUtility db = new DataBaseUtility();

                SqlCommand cm = new SqlCommand();
                string s = DateTime.Now.ToString("MMM/dd/yyyy");

                SqlParameter[] sqlParams = new SqlParameter[]
            {   new SqlParameter("@DBNAME", backupDBName),
                new SqlParameter("@PATH", backupPath),
                new SqlParameter("@BACKUPTYPE", 1),
                new SqlParameter("@MSG", "Genrate Backup"),
                new SqlParameter("@BACKUPFILENAME", s.Replace("/", "_") )};

                db.ExecuteSP("DATABASE_BACKUP", sqlParams);

                log.Info("Backup created success fully with name "+ s.Replace("/", "_"));
            }
            catch (Exception ex)
            {

                log.Info("Exception in  GetDBBackup  ",ex);
            }
        }
开发者ID:RajInternational,项目名称:Subput,代码行数:26,代码来源:RunSchedulerController.cs

示例13: 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

示例14: DataPortal_Fetch

        private void DataPortal_Fetch(CategoryCriteria criteria)
        {
            bool cancel = false;
            OnFetching(criteria, ref cancel);
            if (cancel) return;

            string commandText = String.Format("SELECT [CategoryId], [Name], [Descn] FROM [dbo].[Category] {0}", ADOHelper.BuildWhereStatement(criteria.StateBag));
            using (var connection = new SqlConnection(ADOHelper.ConnectionString))
            {
                connection.Open();
                using (var command = new SqlCommand(commandText, connection))
                {
                    command.Parameters.AddRange(ADOHelper.SqlParameters(criteria.StateBag));
                    using(var reader = new SafeDataReader(command.ExecuteReader()))
                    {
                        if (reader.Read())
                            Map(reader);
                        else
                            throw new Exception(String.Format("The record was not found in 'dbo.Category' using the following criteria: {0}.", criteria));
                    }
                }
            }

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

示例15: GetAllCidades

        public static DataTable GetAllCidades(int estado_id)
        {
            DataTable retorno = new DataTable();
            StringBuilder SQL = new StringBuilder();
            SQL.Append(@"SELECT CidadeId, Nome FROM Cidade WHERE EstadoId = @ESTADO_ID");

            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Mendes_varejo"].ConnectionString))
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand(SQL.ToString(), connection);
                    command.Parameters.AddWithValue("@ESTADO_ID", estado_id);
                    command.ExecuteNonQuery();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(retorno);
                }
            }
            catch (Exception erro)
            {
                throw erro;
            }

            return retorno;
        }
开发者ID:clebermendes,项目名称:mendestec,代码行数:25,代码来源:FornecedorDAO.cs


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