protected void Button1_Click(object sender, EventArgs e) { ErrorLabel.Text = ""; int i = 0; using (SqlConnection conn = new DB().GetConnection()) { string sql = "Update [ResourceFolders] set [email protected] where ID = @FolderID"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@FolderName", FolderName.Text.Trim()); cmd.Parameters.AddWithValue("@FolderID", LabelFolderID.Text); conn.Open(); i = cmd.ExecuteNonQuery(); conn.Close(); //将在Resources表中放在文件夹下的资源都更新文件夹名 { sql = "Update Resources set [email protected] where FolderID = @FolderID"; cmd.CommandText = sql; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); cmd.Dispose(); } } if (i == 1) { ErrorLabel.Text = "媒体信息更新成功!"; Response.Redirect(Server.HtmlEncode("Folder_Man.aspx")); } else { ErrorLabel.Text = "媒体信息更新失败,请重试!"; } }
private void BtnDelete_Click(object sender, EventArgs e) { if (MessageBox.Show("هل ترغب في الاستمرار؟", "تأكــــيد", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.No) { return; } SqlTransaction Trn = null; using (SqlConnection Con = new SqlConnection(FXFW.SqlDB.SqlConStr)) { SqlCommand Cmd = new SqlCommand(String.Format("DELETE FROM CustomersSuppliers WHERE (PERSONID = {0})", LUEItems.EditValue), Con); try { Con.Open(); Trn = Con.BeginTransaction(); Cmd.Transaction = Trn; Cmd.ExecuteNonQuery(); if (CustomerTbl.Rows[LUEItems.ItemIndex]["AccountId"].ToString() != string.Empty) { Cmd.CommandText = "DELETE FROM TBL_Accountes Where AccountId = " + CustomerTbl.Rows[LUEItems.ItemIndex]["AccountId"].ToString(); Cmd.ExecuteNonQuery(); } Trn.Commit(); LoadData(); GetNewAccountID(); LUEItems.ItemIndex = -1; MessageBox.Show("تم الحـــذف ", "حـــــذف", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { Trn.Rollback(); MessageBox.Show(ex.Message); } } }
public bool UpdateEducationlDetail(UserDetails user) { try { SqlCommand com = new SqlCommand(); com.Connection = DbManager.Con; com.CommandType = CommandType.StoredProcedure; com.CommandText = "SP_Update_Education_And_Profession"; com.Parameters.AddWithValue("@Bride_Id", user.Id); com.Parameters.AddWithValue("@Groom_Id", user.Id); com.Parameters.AddWithValue("@Occupation", user.Occupation); com.Parameters.AddWithValue("@Profession_Id", user.Profession_Id); com.Parameters.AddWithValue("@Anual_Incom", user.Anual_Incom); com.Parameters.AddWithValue("@Educational_Qualification", user.Education); com.Parameters.AddWithValue("@Gender", user.Gender); DbManager.Open(); com.ExecuteNonQuery(); return Convert.ToBoolean(com.ExecuteNonQuery()); } catch { throw; } finally { DbManager.Close(); } }
public static void Run() { using (SqlConnection con = new SqlConnection(Helper.GetCurrentDbConnectionString())) { using (SqlCommand cmd = new SqlCommand("Update_Table_ScheduledWork", con)) { string[] sqlfiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "App_Data\\SqlQueries"); con.Open(); // create user defined types before creating stored procedures foreach (string file in sqlfiles.Where(f => f.Contains("Type_Table_Raw"))) { cmd.CommandText = File.ReadAllText(file); cmd.ExecuteNonQuery(); } foreach (string file in sqlfiles.Where(f => f.Contains("StoredProcedure_BulkUpdate"))) { cmd.CommandText = File.ReadAllText(file); cmd.ExecuteNonQuery(); } } } }
protected void ButtonSubmit_Click(object sender, EventArgs e) { string CustId = Request.QueryString["CustId"]; Connection con = new Connection(); string strConnString = con.GetConnString(); using (SqlConnection SqlCon = new SqlConnection(strConnString)) { SqlCommand SqlComm = new SqlCommand("", SqlCon); SqlCon.Open(); int ac_HolderId = Convert.ToInt32(CustId); decimal ac_Blnc = Convert.ToDecimal(TextBoxBlnc.Text); string ac_AltDate = DateTime.Now.ToString(); string query = string.Format("INSERT INTO account(ac_cid, ac_type, ac_blnc, ac_date) VALUES('" + ac_HolderId + "', '" + DropDownListAcType.SelectedValue + "', '" + ac_Blnc + "', '" + ac_AltDate + "')"); SqlComm.CommandText = query; SqlComm.ExecuteNonQuery(); string SetStatus = string.Format("UPDATE cust_details SET c_status='1' WHERE c_id='" + ac_HolderId + "'"); SqlComm.CommandText = SetStatus; SqlComm.ExecuteNonQuery(); General GetNewCode = new General(); string ChqRefNo = GetNewCode.GenerateCode(); string Nartion = "Cash"; string NowDate = DateTime.Now.ToString(); string queryFrTrns = string.Format("INSERT INTO transactions(t_cid, t_nartion, t_refNo, t_deposit, t_blnc, t_date) VALUES('" + ac_HolderId + "', '" + Nartion + "', '" + ChqRefNo + "', '" + ac_Blnc + "', '" + ac_Blnc + "', '" + NowDate + "')"); SqlComm.CommandText = queryFrTrns; SqlComm.ExecuteNonQuery(); Response.Redirect("~/Admin/customer.aspx?CustId="+ CustId + ""); } }
protected void registerBtn_Click(object sender, EventArgs e) { string firstName, lastName, email, username, password, address, mobileNum; firstName = firstNameTxt.Text; lastName = lastNameTxt.Text; email = emailTxt.Text; username = usernameTxt.Text; password = passwordTxt.Text; address = addressTxt.Text; mobileNum = mobileNumTxt.Text; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString); string valCmd = "select UserId,Email from UDetail"; SqlCommand CMD = new SqlCommand(valCmd, con); con.Open(); string cmd = "insert into UDetail values('" + firstName + "','" + lastName + "','" + username + "','" + password + "','" + address + "','" + mobileNum + "','" + email + "') "; SqlCommand Cmd = new SqlCommand(cmd, con); Cmd.ExecuteNonQuery(); Cmd.CommandText = "insert into login values('" + username + "','" + password + "','user')"; Cmd.ExecuteNonQuery(); Response.Cookies["UserId"].Value = username; Response.Cookies["Pwd"].Value = password; //Response.Cookies["role"].Value = "user"; FormsAuthentication.RedirectFromLoginPage(firstName, true); con.Close(); Response.Redirect("register_success.aspx"); }
protected void btnSubmit_Click(object sender, EventArgs e) { string recoverCode = !string.IsNullOrEmpty(Request.QueryString["RecoveryCode"]) ? Request.QueryString["RecoveryCode"] : Guid.Empty.ToString(); using (SqlConnection con = new SqlConnection(Helper.GetCon())) using (SqlCommand cmd = new SqlCommand()) { con.Open(); cmd.Connection = con; cmd.CommandText = "UPDATE Users SET [email protected] FROM Users " + "INNER JOIN Recover ON Users.UserID = Recover.UserID WHERE RecoveryCode" + "[email protected]"; cmd.Parameters.AddWithValue("@recovercode", recoverCode); cmd.Parameters.AddWithValue("@Password", Helper.CreateSHAHash(txtPassword2.Text)); cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM Recover WHERE UserID=" + "(SELECT UserID FROM Users WHERE [email protected])"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@recovercode", recoverCode); cmd.Parameters.AddWithValue("@email", txtEmail.Text); cmd.ExecuteNonQuery(); success.Visible = true; error.Visible = false; } }
private bool DoCardSupply(string cardcode, string money) { System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(); conn.ConnectionString = rms_var.ConnStr; try { SqlCommand selectCMD = new SqlCommand(); selectCMD.CommandTimeout = 30; conn.Open(); selectCMD.Connection = conn; selectCMD.CommandText = "update clubcard set " + "remaincost=remaincost+" + NumericUpDown1.Text + " where clubcardno='" + cardcode + "'"; selectCMD.ExecuteNonQuery(); //记录该次充值记录 selectCMD.CommandText = "insert into CardSupply " + "(clubcardno,supplydate,cost,operator) " + "values " + "(" + "'" + cardcode + "'" + "," + "'" + DateTime.Now.ToString() + "'" + "," + money + "," + "'" + rms_var.opinfo.OpID + "'" + ")"; selectCMD.ExecuteNonQuery(); return true; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return false; } finally { conn.Close(); } }
public override bool Execute() { var conn = SqlServerHelper.GetDatabaseConnection(DatabaseServer, DatabaseUserName, DatabasePassword); try { conn.Open(); var cmd = new SqlCommand(); cmd.Connection = conn; if (SqlServerHelper.DatabaseExists(conn, DatabaseName)) { cmd.CommandText = String.Format(DropDatabase, DatabaseName); cmd.ExecuteNonQuery(); } Log.LogMessage("Creating database {0} on {1}", DatabaseName, DatabaseServer); cmd.CommandText = String.Format("CREATE DATABASE {0}", DatabaseName); cmd.ExecuteNonQuery(); return true; } catch (SqlException ex) { Log.LogErrorFromException(ex, true); return false; } finally { conn.Close(); } }
protected void Button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(constring); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.Connection = con; con.Open(); cmd.CommandText = "insert into schedule(flightid,Flightname,Fromstation,Tostation,dateandtimings,Firstclass,Bussinessclass,economicclass) values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" +TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "')"; int i = cmd.ExecuteNonQuery(); cmd.CommandText = "insert into Fares(flightid,Flightname,Fromstation,Tostation,dateandtimings,firstclass,Bussinessclass,economicclass) values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','"+TextBox5.Text+"','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "')"; int j = cmd.ExecuteNonQuery(); if (i >= 0 && j > 0) { Label.Visible = true; Label.Text = "sucessfully Added"; } else { Label.Visible = true; Label.Text = "Error"; } }
void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { try { BackgroundWorker backgroundWorker = sender as BackgroundWorker; backgroundWorker.ReportProgress(0, "instaling"); using (SqlConnection con = e.Argument as SqlConnection) { string comad1 = System.IO.File.ReadAllText("KillSQL.sql"); string comad2 = System.IO.File.ReadAllText("DeploySQL.sql"); int r; SqlCommand sqlCommand = new SqlCommand(comad1, con); con.Open(); r = sqlCommand.ExecuteNonQuery(); sqlCommand.CommandText = comad2; r = sqlCommand.ExecuteNonQuery(); con.Close(); } } catch (Exception ex) { e.Result = new Tuple<string, bool>("failed " + ex.Message, false); return; } e.Result = new Tuple<string,bool>("success", true ); }
private void button1_Click(object sender, EventArgs e) { string finduser; string r; string u; string s; SqlConnection con1 = Main.connection; con1.Close(); con1.Open(); string insert = "Insert Into[تاریخچه] ([شناسه کالا],[شناسه کارمند],[تاریخ],[توضیحات],[وضعیت]) Values (@id,@uid,@date,@ds,@status); "; SqlCommand command = new SqlCommand(insert, con1); // MessageBox.Show(hid); command.Parameters.Add("@id", AssetID.Text); command.Parameters.Add("@uid",fid); command.Parameters.Add("@date", DateTime.Now); command.Parameters.Add("@ds", Hist_Disc.Text); command.Parameters.Add("@status",Status_Hitory.Text); command.ExecuteNonQuery(); con1.Close(); string update = "Update کالا set وضعیت='"+Status_Hitory.Text+"' where شناسه='"+AssetID.Text+"';"; command.CommandText = update; con1.Open(); command.ExecuteNonQuery(); con1.Close(); // MessageBox.Show("با موفقیت ثبت شد", "پیغام", MessageBoxButtons.OK, MessageBoxIcon.Information); }
//「確定」按鈕事件 protected void btnConfirm_Click(object sender, EventArgs e) { if (tbGroupName.Text != "") //判斷群組名稱是否為空 if (tbGroupPsw.Text == tbGroupPswConfirm.Text) //判斷兩次輸入的密碼是否相同 { //將建立的群組存入PushMessage_TempGroup資料表 //clsHintsDB HintsDB = new clsHintsDB(); try { using (SqlConnection conn = new SqlConnection(strConnString)) { using (SqlCommand comm = new SqlCommand()) { comm.Connection = conn; conn.Open(); string strTempGroupID = "TempGroup_" + DateTime.Now.ToString("yyyyMMddHHmmss");//定義臨時推播訊息群組ID string strSQL = "INSERT INTO PushMessage_TempGroup (cMsgGroupID, cMsgGroupName, cMsgGroupPsw, cUserID) VALUES ('" + strTempGroupID + "','" + tbGroupName.Text + "','" + tbGroupPsw.Text + "','demoUser01')"; comm.CommandText = strSQL; comm.ExecuteNonQuery(); //將人員加入PushMessage_TempGroupMember資料表 strSQL = "INSERT INTO PushMessage_TempGroupMember (cMsgGroupID, cUserID) VALUES ('" + strTempGroupID + "','demoUser01')"; //HintsDB.ExecuteNonQuery(strSQL); comm.CommandText = strSQL; comm.ExecuteNonQuery(); //儲存完後回到訊息模式選擇頁面 Page.RegisterClientScriptBlock("WindowOpen", "<script>window.open('../PushMessage/MessageModeChoose.aspx','MessageModeChoose', 'width=450, height=320, scrollbars=yes');window.close();</script>"); } } }catch { } } else Page.RegisterClientScriptBlock("alert", "<script>alert('兩次輸入的密碼不同,請重新輸入密碼')</script>"); else Page.RegisterClientScriptBlock("alert", "<script>alert('請輸入群組名稱')</script>"); }
protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { if (Page.IsValid) { MessageBox.Show("Account succesfully Registered!", "Account Confirmation"); string Email, UserId; Email = TextBox3.Text; UserId = TextBox7.Text; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString); string valCmd = "select UserId,Email from UDetail"; SqlCommand CMD = new SqlCommand(valCmd, con); con.Open(); string cmd = "insert into UDetail values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox7.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox3.Text + "') "; SqlCommand Cmd = new SqlCommand(cmd, con); Cmd.ExecuteNonQuery(); Cmd.CommandText = "insert into login values('" + TextBox7.Text + "','" + TextBox4.Text + "','user')"; Cmd.ExecuteNonQuery(); Response.Cookies["UserId"].Value = TextBox7.Text; Response.Cookies["Pwd"].Value = TextBox4.Text; //Response.Cookies["role"].Value = "user"; FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true); con.Close(); Response.Redirect("Login.aspx"); } }
public static bool anularPedidoBar(fPrincipal2 fPrincipal, Dictionary<int, int> pedido, int nroHab) { try { SqlCommand comm; comm = new SqlCommand("articulos_anularPedido", fPrincipal2.conn); comm.CommandType = CommandType.StoredProcedure; comm.Parameters.AddWithValue("@nroHab", nroHab); foreach (int nroArt in pedido.Keys) { comm.Parameters.AddWithValue("@nroArt", nroArt); comm.Parameters.AddWithValue("@cant", pedido[nroArt]); comm.ExecuteNonQuery(); // Anular registración en la tabla articulosConsumidos comm.CommandText = "articulosConsumidos_quitar"; comm.ExecuteNonQuery(); //----------------------------------------- comm.Parameters.RemoveAt("@nroArt"); comm.Parameters.RemoveAt("@cant"); comm.CommandText = "articulos_anularPedido"; } tools.actualizarListadoTurnos(fPrincipal.dataGridView1, fPrincipal.dataGridView2); return true; } catch (Exception ex) { throw ex; } }
private static void InsertGroup(MongoServer mongo, MongoDatabase db, SqlCommand cmd) { cmd.CommandText = "delete from DoubanGroups"; cmd.ExecuteNonQuery(); using (mongo.RequestStart(db)) { var collection = db.GetCollection<BsonDocument>("groupinfo_collection"); foreach (var item in collection.FindAll()) { var list = item.RawValues.ToList(); cmd.CommandText = "insert into DoubanGroups values (@v1,@v2,@v3)"; int v2; if (!int.TryParse(list[2].ToString(), out v2)) { v2 = -1; } cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@v1", list[1].ToString()); cmd.Parameters.AddWithValue("@v2", v2); cmd.Parameters.AddWithValue("@v3", list[3].ToString()); cmd.ExecuteNonQuery(); } } }
public int AddExample(List<Knapsack> knapsacks, List<Item> items, double calculateError) { _dbCon.Open(); string qr = @"INSERT INTO Examples(CalculateError) VALUES(" + calculateError + ")"; var dbcom = new SqlCommand(qr, _dbCon); dbcom.ExecuteNonQuery(); qr = "SELECT SCOPE_IDENTITY()"; dbcom.CommandText = qr; int exId = Int32.Parse(dbcom.ExecuteScalar().ToString()); foreach (Knapsack knapsack in knapsacks) { qr = "Insert into Knapsacks(Id,ExampleId,Capacity) VALUES(" + knapsack.Id + "," + exId + "," + knapsack.Capacity + ")"; dbcom.CommandText = qr; dbcom.ExecuteNonQuery(); } foreach (Item item in items) { qr = "Insert into Items(ExampleId,Id,Weight) VALUES(" + exId + "," + item.Id + "," + item.Weight + ")"; dbcom.CommandText = qr; dbcom.ExecuteNonQuery(); } _dbCon.Close(); return exId; }
/// <summary> /// 执行Sql语句 /// </summary> /// <param name="StrSql"></param> public bool ExecuteSql(string StrSql) { System.Data.SqlClient.SqlConnection conn; System.Data.SqlClient.SqlCommand dbCommand; conn = new SqlConnection(mConnectInfo); dbCommand = new SqlCommand(); dbCommand.Connection = conn; dbCommand.CommandTimeout = 36000; try { conn.Open(); //建立数据库连接 dbCommand.CommandText = "set quoted_identifier off"; dbCommand.ExecuteNonQuery(); dbCommand.CommandText = StrSql; dbCommand.ExecuteNonQuery(); return true; } catch (System.Data.SqlClient.SqlException e) { throw new Exception(e.Message); } finally { conn.Close(); } } //ExecuteSql
protected void btnSubmit_Click(object sender, EventArgs e) { if (Session["userid"] != null) { con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = "INSERT INTO Messages VALUES (@Category, @MessageCat, @Subject, " + "@DateSubmitted, @Message, @UserID, @Email, @Status)"; cmd.Parameters.AddWithValue("@Category", "Frontpage"); cmd.Parameters.AddWithValue("@Subject", txtSubject.Text.ToString()); cmd.Parameters.AddWithValue("@MessageCat", "Message"); cmd.Parameters.AddWithValue("@DateSubmitted", DateTime.Now); cmd.Parameters.AddWithValue("@Message", txtMessage.Text.ToString()); cmd.Parameters.AddWithValue("@UserID", Session["UserID"].ToString()); cmd.Parameters.AddWithValue("@Email", txtEmail.Text.ToString()); cmd.Parameters.AddWithValue("@Status", "Unread"); cmd.ExecuteNonQuery(); cmd.CommandText = "UPDATE Users SET [email protected] WHERE [email protected]"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@Priority", "Contact Immediately"); cmd.Parameters.AddWithValue("@UserID", Session["userid"].ToString()); cmd.ExecuteNonQuery(); con.Close(); Helper.Log(Session["userid"].ToString(), "Frontpage", "Message", ""); EmailNotification(); } else { Response.Redirect("~/Account/Login.aspx"); } }
protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { if (Page.IsValid) { string Email, UserId; Email = TextBox3.Text; UserId = TextBox7.Text; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["shopingConnectionString1"].ConnectionString); string valCmd = "select UserId,Email from UDetail"; SqlCommand CMD = new SqlCommand(valCmd, con); con.Open(); string cmd = "insert into UDetail values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox7.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox3.Text + "') "; SqlCommand Cmd = new SqlCommand(cmd, con); Cmd.ExecuteNonQuery(); Cmd.CommandText = "insert into login values('" + TextBox7.Text + "','" + TextBox4.Text + "','user')"; Cmd.ExecuteNonQuery(); Response.Cookies["uname"].Value = TextBox7.Text; Response.Cookies["pwd"].Value = TextBox4.Text; Response.Cookies["role"].Value = "user"; FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true); con.Close(); } }
static void Main(string[] args) { String sc = "Data Source=.\\sqlexpress;Initial Catalog=MASTER;Integrated Security=true;"; using (SqlConnection c = new SqlConnection(sc)) { String cmd = "CREATE DATABASE VS2010"; using (SqlCommand k = new SqlCommand(cmd, c)) { //SqlCommand faz parte do modelo CONECTADO //ExecuteNonQuery retorna o número de linhas afetadas c.Open(); k.ExecuteNonQuery(); c.ChangeDatabase("VS2010"); k.CommandText = "CREATE TABLE PESSOA (COD_PESSOA INT, NOME_PESSOA VARCHAR(50), SEXO_PESSOA CHAR(1))"; k.ExecuteNonQuery(); c.Close(); } } Console.WriteLine("funcionou"); Console.ReadKey(); }
private void buttonDev_Click(object sender, EventArgs e) { // MessageBox.Show("Todavia no esta el procedure"); SqlTransaction transaction = Conexion.getConexion().BeginTransaction(); try { SqlCommand cmd = new SqlCommand("exec THE_CVENGERS.crearDevolucion @compra = " + idComp + ", @descripcion= '" + razonText.Text + "'", Conexion.getConexion()); cmd.Transaction = transaction; cmd.ExecuteNonQuery(); // MessageBox.Show(cmd.CommandText); foreach (object dev in checkedListBox1.CheckedItems) { cmd.CommandText = "exec THE_CVENGERS.devolverItem @item = " + ((ItemsDevolucion)dev).getNumero() + ", @tipoItem = '" + ((ItemsDevolucion)dev).getTipo() + "'"; cmd.ExecuteNonQuery(); // MessageBox.Show(cmd.CommandText); } transaction.Commit(); } catch (Exception exc) { if(exc is SqlException) transaction.Rollback(); MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK); } mandarMensajeDeExito(); razonText.ResetText(); for (int i = 0; i < checkedListBox1.Items.Count; i++) checkedListBox1.SetItemCheckState(i, (CheckState.Unchecked)); checkedListBox1.Refresh(); foreach (int it in checkedListBox1.CheckedIndices) { checkedListBox1.Items.RemoveAt(it); } lleni.llenarDataGridViewDevolucion(dataGridView1, idClie); dataGridView1.ClearSelection(); }
public void SetupDatabase() { var cfg = new Cfg.Configuration(); var connStr = cfg.Properties["connection.connection_string"]; using (var conn = new SqlConnection(connStr)) { conn.Open(); using (var cmd = new System.Data.SqlClient.SqlCommand("use master", conn)) { cmd.ExecuteNonQuery(); cmd.CommandText = "drop database nhibernate"; try { cmd.ExecuteNonQuery(); } catch(Exception) { } cmd.CommandText = "create database nhibernate"; cmd.ExecuteNonQuery(); } } }
private void button3_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection(//创建数据库连接对象 @"server=(local);Pwd=6221131;uid=sa;database=master")) { try { SqlCommand cmd = new SqlCommand();//创建命令对象 cmd.Connection = con;//设置连接属性 cmd.Connection.Open();//打开数据库连接 cmd.CommandText =//设置要执行的存储过程 @"sp_configure 'xp_cmdshell',1 reconfigure"; cmd.ExecuteNonQuery();//执行存储过程 string str = "xp_cmdshell 'copy "//创建SQL字符串 + this.textBox1.Text + " "; str += "" + this.textBox2.Text + "'";//组合SQL字符串 cmd.CommandText = str;//设置要执行的SQL语句 cmd.ExecuteNonQuery();//执行SQL语句 this.label3.Text = "已成功完成信息拷贝";//显示提示信息 } catch (Exception ey) { MessageBox.Show(ey.Message);//弹出消息对话框 } } }
protected void ButInput_Click(object sender, System.EventArgs e) { //���浽���ݿ� int i=0; string strConn=ConfigurationSettings.AppSettings["strConn"]; SqlConnection ObjConn =new SqlConnection(strConn); ObjConn.Open(); SqlTransaction ObjTran=ObjConn.BeginTransaction(); SqlCommand ObjCmd=new SqlCommand(); ObjCmd.Transaction=ObjTran; ObjCmd.Connection=ObjConn; try { ObjCmd.CommandText="Update UserInfo set DeptID=0 where DeptID="+intDeptID+""; ObjCmd.ExecuteNonQuery(); for(i=0;i<LBSelected.Items.Count;i++) { ObjCmd.CommandText="Update UserInfo set DeptID="+intDeptID+" where UserID="+LBSelected.Items[i].Value+""; ObjCmd.ExecuteNonQuery(); } ObjTran.Commit(); } catch { ObjTran.Rollback(); } finally { ObjConn.Close(); ObjConn.Dispose(); } this.RegisterStartupScript("newWindow","<script language='javascript'>window.close();</script>"); }
protected void Page_Load(object sender, EventArgs e) { string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; using (SqlConnection con = new SqlConnection(CS)) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "Insert into tblProduct values (4, 'Calculators', 100, 230)"; cmd.Connection = con; con.Open(); //DELETE cmd.CommandText = " Delete from tblProduct where ProductId = 4"; int TotalRowsAffected = cmd.ExecuteNonQuery(); Response.Write("Total Rows Deleted= " + TotalRowsAffected.ToString() + "</br>"); //INSERT cmd.CommandText = " Insert into tblProduct values (4, 'Calculators', 100, 230)"; TotalRowsAffected = cmd.ExecuteNonQuery(); Response.Write("Total Rows Inserted= " + TotalRowsAffected.ToString() + "</br>"); //UPDATE cmd.CommandText = " update tblProduct set QtyAvailable = 200 where ProductId = 2"; TotalRowsAffected = cmd.ExecuteNonQuery(); Response.Write("Total Rows Updated= " + TotalRowsAffected.ToString() + "</br>"); //Exexute Scalar to return one value.- sql = Select Count(ProductId) From tblProduct //int TotalRows = (int)cmd.ExecuteScalar(); //Response.Write("Total Rows= " + TotalRows.ToString()); //Execute Reader Method. //GridView1.DataSource = cmd.ExecuteReader(); //GridView1.DataBind(); } }
public bool UpdatePersionalDetail(UserDetails user) { try { SqlCommand com = new SqlCommand(); com.Connection = DbManager.Con; com.CommandType = CommandType.StoredProcedure; com.CommandText = "SP_Update_Persional_Details"; com.Parameters.AddWithValue("@Bride_Id", user.Id); com.Parameters.AddWithValue("@Groom_Id", user.Id); com.Parameters.AddWithValue("@Height", Convert.ToInt32( user.Height)); com.Parameters.AddWithValue("@About_Me", user.About_Me); com.Parameters.AddWithValue("@About_My_Patner", user.About_My_Patner); com.Parameters.AddWithValue("@Physical_Status", user.Physical_Status); com.Parameters.AddWithValue("@Weight", user.Weight); com.Parameters.AddWithValue("@Gender", user.Gender); DbManager.Open(); com.ExecuteNonQuery(); return Convert.ToBoolean(com.ExecuteNonQuery()); } catch { throw; } finally { DbManager.Close(); } }
public override void ExecuteDetachDatabase(string dbName, IDbConnection conn) { // matar todos os processos no sqlServer que utilizem a BD GISA string cmdText= string.Format( "DECLARE @sql VARCHAR(500) " + "SET @sql = '' " + "SELECT @sql = @sql + ' KILL ' + CAST(procs.spid AS VARCHAR(10)) + ' ' " + "FROM master.dbo.sysprocesses procs " + "WHERE DB_NAME(procs.dbid) like 'GISA' " + "AND procs.spid > 50 AND procs.spid <> @@SPID " + "EXEC(@sql)", dbName); SqlCommand command = new SqlCommand(cmdText, (SqlConnection) conn); command.ExecuteNonQuery(); // detach da BD command.CommandText = "sp_detach_db"; command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@dbname", SqlDbType.NVarChar); command.Parameters[0].Value = dbName; command.Parameters.Add("@skipchecks", SqlDbType.NVarChar); command.Parameters[1].Value = System.DBNull.Value.ToString(); command.ExecuteNonQuery(); }
private void BtnUpdate_Click(object sender, EventArgs e) { using (SqlConnection Con = new SqlConnection(FXFW.SqlDB.SqlConStr)) { SqlCommand Cmd = new SqlCommand("", Con); SqlTransaction trn = null; try { Con.Open(); trn = Con.BeginTransaction(); Cmd.Transaction = trn; Cmd.CommandText = string.Format("Delete From UserRoles Where UserId = {0}", LUEItems.EditValue); Cmd.ExecuteNonQuery(); foreach (DataRow row in RolesTbl.Rows) { if (row["Active"].ToString() == "1") { Cmd.CommandText = String.Format("INSERT INTO UserRoles (UserId, RoleId) VALUES ({0}, {1})", LUEItems.EditValue, row["RoleID"].ToString()); Cmd.ExecuteNonQuery(); } } trn.Commit(); LoadRoles(LUEItems.EditValue.ToString()); Program.ShowMsg("تم التعديل ..", false, this); Program.Logger.LogThis("تم التعديل ..", Text, FXFW.Logger.OpType.success, null, null, this); } catch (Exception ex) { trn.Rollback(); MessageBox.Show(ex.Message); Program.Logger.LogThis(null, Text, FXFW.Logger.OpType.fail, ex, null, this); } } }
private static void InsertKunden() { using (SqlConnection myConnection = new SqlConnection(ConnectionString)) { SqlCommand myCommand = new SqlCommand(); myCommand.Connection = myConnection; // Open the connection. myConnection.Open(); SetAutoIncrementOnTable(myConnection, "Kunde", false); myCommand.CommandText = "INSERT INTO Kunde (Id, Nachname, Vorname, Geburtsdatum) VALUES (1, 'Nass', 'Anna', '05/05/1961')"; myCommand.ExecuteNonQuery(); myCommand.CommandText = "INSERT INTO Kunde (Id, Nachname, Vorname, Geburtsdatum) VALUES (2, 'Beil', 'Timo', '09/09/1980')"; myCommand.ExecuteNonQuery(); myCommand.CommandText = "INSERT INTO Kunde (Id, Nachname, Vorname, Geburtsdatum) VALUES (3, 'Pfahl', 'Martha', '07/03/1950')"; myCommand.ExecuteNonQuery(); myCommand.CommandText = "INSERT INTO Kunde (Id, Nachname, Vorname, Geburtsdatum) VALUES (4, 'Zufall', 'Rainer', '11/11/1944')"; myCommand.ExecuteNonQuery(); SetAutoIncrementOnTable(myConnection, "Kunde", true); } }