protected void Button3_Click(object sender, EventArgs e) { String s = ConfigurationManager.ConnectionStrings["MediDB"].ConnectionString; SqlConnection con = new SqlConnection(s); SqlCommand cmd = new SqlCommand(" Select Count(*) from Admin where name='" + TextBox1.Text + "' and Password='" + TextBox2.Text + "'", con); con.Open(); int m = (int)cmd.ExecuteScalar(); if (m == 1) { Button1.Enabled = true ; Button2.Enabled = true ; Button4.Enabled = true ; Button5.Enabled = true ; } else { Response.Write("<Script>alert('Name or the password entered by you is incorrect. please try again!!')</Script>"); } cmd.ExecuteScalar(); con.Close(); TextBox1.Text = ""; TextBox2.Text = ""; }
protected void Tmbtn_Click(object sender, EventArgs e) { SqlCommand cmd = new SqlCommand("select MAX(wjh) from wj", cn); cn.Open(); cmd.ExecuteScalar(); //cn.Close(); SqlCommand com = new SqlCommand("INSERT INTO Tm(Wjh,Tm,Tixing) VALUES (" +cmd.ExecuteScalar()+ ",'" + Tmtxt.Text.Trim() + "','" + TXDropDownList.Text.Trim() + "')", cn); //com.ExecuteNonQuery(); //cn.Close(); try { //cn.Open(); int val = com.ExecuteNonQuery(); cn.Close(); this.NRListBox.Items.Add(this.Tmtxt.Text); if (val <= 0) ClientScript.RegisterStartupScript(this.GetType(), "", "alert('插入数据失败!')"); else ClientScript.RegisterStartupScript(this.GetType(), "", "alert('插入数据成功!')"); } //捕获异常 catch (Exception exp) { //处理异常....... ClientScript.RegisterStartupScript(this.GetType(), "", "alert('插入数据失败! 详情:" + exp.Message + "')"); } }
public static bool Grabar(Entidades.Distrito pEntidad) { using (var cn = new SqlConnection(conexion.LeerCC)) { // Contamos cuantos distritos existen segun el coddistrito o nomdistrito using (var cmd = new SqlCommand(@"select isnull(count(coddistrito),0) from distritos where [email protected] or [email protected]", cn)) { cmd.Parameters.AddWithValue("cod", pEntidad.coddistrito); cmd.Parameters.AddWithValue("nom", pEntidad.nomdistrito); cn.Open(); // Ejecutamos el comando y verificamos si el resultado es mayor a cero actualizar, caso contrario insertar if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) { // Si es mayor a cero, quiere decir que existe al menos un registro con los datos ingresados // Entonces antes de actualizar, hacer las siguientes comprobaciones if (pEntidad.coddistrito == 0) throw new Exception("El distrito ya esta registrado en el sistema, verifique los datos por favor!..."); // Verifica si ya existe un registro con el mismo nombre del distrito cmd.CommandText = @"select isnull(count(coddistrito),0) from distritos where coddistrito<>@cod and [email protected]"; if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) throw new Exception("No se puede grabar un valor duplicado, verifique los datos por favor!..."); // Si las comprobaciones anteriores resultaron ser falsa, entonces actualizar cmd.CommandText = @"update distritos set [email protected] where [email protected]"; } else cmd.CommandText = @"insert into distritos (nomdistrito) values (@nom)"; // Ejecutamos el comando que puede ser para update o insert return Convert.ToBoolean(cmd.ExecuteNonQuery()); } } }
protected void Button1_Click(object sender, EventArgs e) { SqlCommand cmd=new SqlCommand("select password from consumer where email='"+TextBox1.Text+"'",con); con.Open(); if (cmd.ExecuteScalar()!=null) { string s = cmd.ExecuteScalar().ToString(); MailMessage mail = new MailMessage(); mail.To.Add(TextBox1.Text); mail.From = new MailAddress("[email protected]"); mail.Subject = "Remember Mail"; string Body = "Password is " + s; mail.Body = Body; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.UseDefaultCredentials = false; smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "9232663223"); smtp.EnableSsl = true; smtp.Send(mail); Label1.Text = "PASSWORD SENT TO YOUR EMAIL ADDRESS"; con.Close(); } else Label1.Text = "No such email exists "; }
/// <summary> /// Performs a scalar select and returns the value as a string /// </summary> /// <param name="qS"></param> /// <returns></returns> public static String ScalarString(String qS) { object returnValue = ""; SqlConnection con = new SqlConnection(ConnectionString); SqlCommand cmd = new SqlCommand(qS, con); using (con) { if (con.State == ConnectionState.Open) { returnValue = cmd.ExecuteScalar(); con.Close(); } else { con.Open(); returnValue = cmd.ExecuteScalar(); con.Close(); } } if (returnValue == null) { return ""; } else return returnValue.ToString(); }
/// <inheritdoc/> public bool CorrelativeConfigurationExists(string facilityId, string correlativeId) { if (string.IsNullOrWhiteSpace(facilityId)) return false; if (string.IsNullOrWhiteSpace(correlativeId)) return false; if (string.IsNullOrWhiteSpace(_connectionString)) return false; int count; using (var conexionSp = new SqlConnection(_connectionString)) { const string query = "SELECT COUNT(PaqueteId) FROM Comunes.CorrelativosPaquetes " + "WHERE PaqueteId = @correlativeId AND PlantaId = @facilityId"; using (var comandoSp = new SqlCommand(query, conexionSp)) { comandoSp.CommandType = CommandType.Text; comandoSp.Parameters.AddWithValue("@correlativeId", correlativeId).Direction = ParameterDirection.Input; comandoSp.Parameters.AddWithValue("@facilityId", facilityId).Direction = ParameterDirection.Input; conexionSp.Open(); count = comandoSp.ExecuteScalar() is int ? (int)comandoSp.ExecuteScalar() : 0; conexionSp.Close(); } } return count > 0; }
public static int? getMax() { int? id = null; string conexionCadena = ConfigurationManager.ConnectionStrings["ConexionComplejo"].ConnectionString; SqlConnection con = new SqlConnection(); try { con.ConnectionString = conexionCadena; con.Open(); string sql = "SELECT MAX(id_fact) from facturas"; SqlCommand cmd = new SqlCommand(); cmd.CommandText = sql; cmd.Connection = con; if(!cmd.ExecuteScalar().Equals(null)) { id =(int) cmd.ExecuteScalar(); } else { id = null; } } catch (SqlException ex) { throw new ApplicationException("Error al traer max id cliente" + ex.Message); } finally { con.Close(); } return id; }
public RequestsProcessedByEnum GetLeaveStatus(int leaveRequestId) { SqlConnection conn = null; SqlCommand cmd = null; try { conn = DALHelper.CreateSqlDbConnection(); cmd = new SqlCommand("usp_GetLeaveStatus", conn); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@LeaveRequestId", leaveRequestId); if (cmd.ExecuteScalar() != DBNull.Value) { return (RequestsProcessedByEnum)Convert.ToInt32(cmd.ExecuteScalar()); } else { return RequestsProcessedByEnum.NotDefined; } } catch (Exception) { throw; } finally { conn.Close(); cmd.Dispose(); conn.Dispose(); } }
/// <summary> /// Authenticates the user /// </summary> /// <param name="user">user from login form</param> /// <param name="password">password from login form</param> public static bool Authenticate(String user,String password) { var positiveIntRegex = new Regex(@"^\w+$"); if (!positiveIntRegex.IsMatch(user)) { return false; } if (!positiveIntRegex.IsMatch(password)) { return false; } String encryptedPass = Encrypt(password); string constr = Settings.Default.UserDbConnectionString; SqlConnection con = new SqlConnection(constr); SqlCommand command = new SqlCommand(); command.Connection = con; command.Parameters.AddWithValue("@Username", user); command.CommandText = "SELECT Password FROM Users WHERE Name = @Username"; command.CommandType = CommandType.Text; con.Open(); string _password = ""; if (command.ExecuteScalar() != null) _password = command.ExecuteScalar().ToString(); else return false; con.Close(); if (encryptedPass.Equals(_password)) { return true; } return false; }
public static string ExecuteScalar(string strSql) { try { iniCon(); SqlConnection sCon=new SqlConnection(m_strCon); sCon.Open(); SqlCommand sCmd=new SqlCommand(); sCmd.Connection =sCon ; sCmd.CommandText =strSql; if(sCmd.ExecuteScalar()!=null) { string strRet=sCmd.ExecuteScalar().ToString(); sCon.Close(); return strRet; } else { sCon.Close(); return ""; } }catch(Exception ex) { MessageBox.Show(ex.ToString()); Application.Exit(); //MessageBox.Show(ex.ToString()); return ""; } }
protected void login_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("server=(localdb)\\v11.0;Initial Catalog=WebApplication2;Integrated Security=true"); con.Open(); string str = "select count(*) from Users where userName='" + username.Text + "'"; SqlCommand command = new SqlCommand(str, con); int temp = Convert.ToInt32(command.ExecuteScalar().ToString()); if (temp == 1) { string str2 = "select password from Users where userName='" + username.Text + "'"; SqlCommand command2 = new SqlCommand(str2, con); string tempPass = command2.ExecuteScalar().ToString().ToLower().Trim(); if (tempPass==pass.Text.ToLower().Trim()) { string str3 = "select user_id from Users where userName='" + username.Text + "'"; SqlCommand command3 = new SqlCommand(str3, con); temp = Convert.ToInt32(command.ExecuteScalar().ToString()); con.Close(); Session["new"] = temp; Response.Redirect("Home.aspx"); } else { Label1.Visible = true; Label1.Text = "Wrong password!"; } } else { Label1.Visible = true; Label1.Text = "Invalid user name!"; } }
public List<TableInfo> LoadTableList(string databaseConnectionString) { List<TableInfo> tables; using (var conn = new SqlConnection(databaseConnectionString)) { conn.Open(); var cmd = new SqlCommand(SqlQueries.QUERY_ALL_TABLES, conn); using (var reader = cmd.ExecuteReader()) { tables = new List<TableInfo>(); while (reader.Read()) { tables.Add(new TableInfo(reader.GetString(0), reader.GetString(1))); } } int tableCount = 0; foreach (var tableInfo in tables) { cmd = new SqlCommand(string.Format(SqlQueries.QUERY_DATA_SIZE, tableInfo.Name, tableInfo.Schema), conn); cmd.CommandTimeout = 60000; tableInfo.DataSizeBytes = (double) cmd.ExecuteScalar(); cmd.CommandText = string.Format(SqlQueries.QUERY_INDEX_SIZE, tableInfo.Name, tableInfo.Schema); tableInfo.IndexSizeBytes = (double) cmd.ExecuteScalar(); cmd.CommandText = string.Format(SqlQueries.QUERY_ROW_COUNT, tableInfo.Name, tableInfo.Schema); tableInfo.RowCount = (long) cmd.ExecuteScalar(); OnTableLoadProgressChanged(new ProgressEventArgs(tableCount++*100 / tables.Count)); } } return tables; }
public string generatestudentcode() { string regcode = ""; string query = "select RegistrationCode from StudentPersonalInformation where ID =(select Max(ID) from StudentPersonalInformation)"; try { SqlCommand cmd = new SqlCommand(query, con); if (con.State == ConnectionState.Closed) con.Open(); if (cmd.ExecuteScalar() != null) { //regcode = cmd.ExecuteScalar().ToString(); //regcode= regcode.Substring(0,regcode.LastIndexOf('/')-1) + Convert.ToInt32(regcode.Substring(regcode.LastIndexOf('/'), (regcode.Length - (regcode.LastIndexOf('/'))) + 1)) +1; regcode = (Convert.ToInt32(cmd.ExecuteScalar()) + 1).ToString(); } else regcode = "1"; // regcode = "ASTM/" + DropDownListCenter.SelectedValue + "/" + DateTime.Now.Year + "/1"; // regcode = "ASTM/" + DropDownListCenter.Items[0].Text + "/" + DropDownListCourse.SelectedValue + "/" + DateTime.Now.Year + "/1"; } catch (Exception ex) { } finally { con.Close(); } return regcode; }
void GetCurrentMembership() { string userID = Session["UserID"].ToString(); if (CheckMembership()) { using (SqlConnection con = new SqlConnection(Helper.GetCon())) using (SqlCommand cmd = new SqlCommand()) { con.Open(); cmd.Connection = con; cmd.CommandText = "SELECT SUM(Length) FROM Memberships INNER JOIN Payments ON " + "Memberships.MembershipID=Payments.MembershipID WHERE [email protected] " + "AND MembershipStatus='Active' AND PaymentStatus='Paid'"; cmd.Parameters.AddWithValue("@UserID", userID); int totalYears = (int)cmd.ExecuteScalar(); cmd.CommandText = "SELECT TOP 1 StartDate FROM Memberships INNER JOIN Payments ON " + "Memberships.MembershipID=Payments.MembershipID WHERE [email protected] " + "AND MembershipStatus='Active' AND PaymentStatus='Paid'"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@UserID", userID); DateTime endDate = (DateTime)cmd.ExecuteScalar(); DateTime totalEndDate = endDate.AddYears(totalYears); txtEndDate.Text = totalEndDate.ToString("D"); } } else { txtEndDate.Text = "N/A"; nomem.Visible = true; btnDisable.Visible = false; btnEnable.Visible = false; } }
//----------------------------------- public void favoritecontrol() { try { if (Session["userid"] != null) { myconnection.Open(); SqlCommand com = new SqlCommand("SPfavoritecontrol", myconnection); com.CommandType = CommandType.StoredProcedure; com.Parameters.Add("@movieid", SqlDbType.Int); com.Parameters["@movieid"].Value = Convert.ToInt32(Request.QueryString["movieid"]); com.Parameters.Add("@userid", SqlDbType.Int); com.Parameters["@userid"].Value = Convert.ToInt32(Session["userid"]); if (com.ExecuteScalar() != null) { if (Convert.ToInt32(com.ExecuteScalar().ToString()) != 0) { LinkButtonaddtofavorites.Text = "Added to favorites"; } } } } catch (Exception ex) { Labelerror.Text = "error in controlling favorites" + ex.Message; } finally { myconnection.Close(); } }
/// <summary> /// Check Employee whether exist /// </summary> /// <param name="employeeId"></param> /// <returns></returns> public bool IsEmployeeIdExist(string employeeId) { using (SqlConnection conn = new SqlConnection(DBHelper.GetConnection())) { SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = @"select EmployeeId from dbo.Employee where EmployeeId = @EmployeeId"; cmd.Parameters.AddWithValue("@EmployeeId", employeeId); bool result = false; try { conn.Open(); cmd.ExecuteScalar(); if (cmd.ExecuteScalar() != null) { result = true; } } catch (Exception ex) { } finally { cmd.Dispose(); conn.Close(); } return result; } }
public CanUploadStatus CanUpload(string filename, int size) { bool extAllowed = FileExtensionAllowed(filename); if (!extAllowed) return CanUploadStatus.FileTypeNotAllowed; else { int uploaded = 0; using (var dbContext = _dbService.GetDatabaseContext(false)) { SqlCommand cmd = new SqlCommand(@" select SUM(f.Size) from [File] f inner join [File_User_Access] as fua ON fua.lid = f.Id inner join [User] u on u.Id = fua.rid where u.Id = @userId", dbContext.Connection); cmd.Parameters.AddWithValue("userId", _securityService.CurrentUser.Id); var raw = cmd.ExecuteScalar(); if (raw != DBNull.Value) uploaded = (int)cmd.ExecuteScalar(); else uploaded = 0; } if (uploaded > _securityService.CurrentUser.GetData<int>("DiskUsageLimit")) return CanUploadStatus.DiskUsageLimitExceeded; else return CanUploadStatus.Yes; } }
public int GetInformationAssistantCount(string employeeId) { using (SqlConnection conn = new SqlConnection(DBHelper.GetConnection())) { SqlCommand cmd = new SqlCommand(); int result = 0; cmd.Connection = conn; cmd.CommandText = @"select count(*) as InformationAssistantCount, e.Name as EmployeeName from Employee e ,InformationAssistant i where e.EmployeeId = i.EmployeeId and e.EmployeeId = @EmployeeId and CONVERT(varchar(100), i.RecordDate, 111)=CONVERT(varchar(100), getdate(), 111) group by e.Name"; cmd.Parameters.AddWithValue("@EmployeeId", employeeId); try { conn.Open(); result = DBNull.Value == cmd.ExecuteScalar() ? 0 : Convert.ToInt32(cmd.ExecuteScalar()); } catch (Exception ex) { throw ex; } finally { conn.Close(); cmd.Dispose(); } return result; } }
/// <summary> /// This method Returns the object after executing the execute scalar method /// </summary> /// <param name="cmdClass"></param> /// <param name="objExp"></param> public int ExecuteScalar(SqlCommand cmdClass, out Object obj, out Exception objExp) { int intStatus = 0; obj = null; objExp = null; try { SqlConnection conClass = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString); cmdClass.Connection = conClass; if (conClass.State == ConnectionState.Closed) conClass.Open(); if (cmdClass.ExecuteScalar() != DBNull.Value) obj = cmdClass.ExecuteScalar(); else obj = null; conClass.Close(); conClass.Dispose(); cmdClass.Dispose(); if (obj != null) intStatus = 1; } catch (Exception exp) { objExp = exp; } return (intStatus); }
/// <summary> /// Attempts to purchase a movie for a user /// </summary> /// <param name="movieId">The movie to purchase</param> /// <param name="userId">The user purchasing the movie</param> /// <returns>true if the movie is bought, false if the movie could not be bought (f.ex. due to insufficient funds)</returns> public bool PurchaseMovie(int movieId, int userId) { //Ensure that the id is valid for a movie SqlCommand command = new SqlCommand("SELECT id FROM Movie WHERE id=" + movieId, connection); if (command.ExecuteScalar() == null) return false; //Get the price of the movie command.CommandText = "SELECT buyPrice FROM Files WHERE id =" + movieId; Object pric = command.ExecuteScalar(); if (pric == null) return false; int price = (int)pric; //Get the balance of the user command.CommandText = "SELECT balance FROM Users WHERE id =" + userId; Object bal = command.ExecuteScalar(); if (bal == null) return false; int balance = (int)bal; if (balance - price >= 0) { //Withdraw the amount from the users balance and only continue if it is successful command.CommandText = "UPDATE Users " + "SET balance = balance - " + price + "WHERE id = " + userId; if (command.ExecuteNonQuery() > 0) { command.CommandText = "INSERT INTO UserFile " + "VALUES(" + userId + ", " + movieId + ", '" + DateTime.MaxValue.ToString("yyyy-MM-dd HH:mm:ss") + "' )"; return command.ExecuteNonQuery() > 0; } } return false; }
protected void btnEdit_Click(object sender, EventArgs e) { string connectionstring = WebConfigurationManager.ConnectionStrings["SCSDataBase"].ConnectionString; SqlConnection con = new SqlConnection(connectionstring); try { con.Open(); SqlCommand cmd = new SqlCommand("exec getUserControlledPupilId @lg", con); cmd.Parameters.Add("@lg", login); string pId = ((int)cmd.ExecuteScalar()).ToString(); cmd.CommandText = "exec getUserAccess @lg"; int access = (int)cmd.ExecuteScalar(); if (access >= 2) { cmd.CommandText = "exec getPupilFLF @pid"; cmd.Parameters.Add("@pid", pId); string flf = (string)cmd.ExecuteScalar(); con.Close(); Session["SCSTitle"] = flf; Session["SCSParameter1"] = pId; Response.Redirect("Redactor.aspx"); } else { Response.Write("<div align=center>Вашего уровня допуска недостаточно для этой операции <BR> <a href='ChangeAccess.aspx'>Как изменить уровень допуска?</A> " + "<BR>Ваш текущий уровень допуска : " + access.ToString() + " Требуемый : 2</div>"); } } catch (Exception err) { Response.Write(err.Message); } }
protected void Button1_Click(object sender, EventArgs e) { if(TextBox3.Text==TextBox4.Text && TextBox1.Text!=""&&TextBox2.Text!=""&&TextBox5.Text!="") { cmd=new SqlCommand("select did from cities where [email protected]",con); con.Open(); cmd.Parameters.AddWithValue("@city",TextBox5.Text); if(cmd.ExecuteScalar()==null) Label2.Text="City not available"; else { int did=int.Parse(cmd.ExecuteScalar().ToString()); cmd=new SqlCommand("insert into distributorapplication values(@d,@did,@u,@p,@c)",con); cmd.Parameters.AddWithValue("@d",TextBox1.Text); cmd.Parameters.AddWithValue("@did",did); cmd.Parameters.AddWithValue("@u",TextBox2.Text); cmd.Parameters.AddWithValue("@p",TextBox3.Text); cmd.Parameters.AddWithValue("@c", TextBox5.Text); cmd.ExecuteNonQuery(); Label2.Text="Request for registration sent to administrator. You will be notified within few dayd"; TextBox1.Text = TextBox2.Text = TextBox5.Text = ""; } con.Close(); } else if(TextBox3.Text!=TextBox4.Text) Label2.Text="Password doesn't match"; else { Label2.Text="Please fill in all the details"; } }
public int GetCustomerId() { using (SqlConnection conn = new SqlConnection(DBHelper.GetConnection())) { int result = 0; SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = @"select max(CustomerId) from Customer"; try { conn.Open(); result = cmd.ExecuteScalar() == DBNull.Value ? 0 : Convert.ToInt32(cmd.ExecuteScalar()); } catch (Exception ex) { throw ex; } finally { conn.Close(); cmd.Dispose(); } return result + 1; } }
protected void btnAccept_Click(object sender, EventArgs e) { string constr = WebConfigurationManager.ConnectionStrings["SCSDataBaseAdminLogin"].ConnectionString; constr = constr.Replace("ID=admin;Password=;", "ID=SCSAdmin;Password=" + tbAdminPassword.Text + ";"); SqlConnection con = new SqlConnection(constr); try { con.Open(); SqlCommand cmd = new SqlCommand("exec ChangeAccess @lg, @na", con); cmd.Parameters.Add("@lg", lblLogin.Text); cmd.Parameters.Add("@na", Convert.ToInt32(lblNeedAccess.Text)); cmd.ExecuteScalar(); cmd.CommandText = "exec CreateNewMessage @lgself, @lg, 'Запрос выполнен'"; cmd.Parameters.Add("@lgself", login); cmd.ExecuteScalar(); con.Close(); Response.Redirect("Cabinet.aspx"); } catch (Exception err) { //Response.Clear(); Response.Write(err.Message); } finally { con.Close(); } }
public static void insertarReserva(Reserva res, DetalleReserva det) { string connStr = ConfigurationManager.ConnectionStrings["ConexionComplejo"].ConnectionString; SqlConnection cn = new SqlConnection(); SqlTransaction tran = null; try { cn.ConnectionString = connStr; cn.Open(); tran = cn.BeginTransaction(); string sql = "INSERT INTO RESERVAS (fecha_res,cli_id,estado,monto) values (@FechaRes,@Cliente,@Estado,@Monto); SELECT @@Identity as ID;"; SqlCommand cmd = new SqlCommand(); cmd.CommandText = sql; cmd.Connection = cn; cmd.Transaction = tran; cmd.Parameters.AddWithValue("@FechaRes",res.Fecha); cmd.Parameters.AddWithValue("@Cliente", res.Cli.IdCliente); cmd.Parameters.AddWithValue("@Estado", res.Estado); cmd.Parameters.AddWithValue("@Monto", res.Monto); res.Id = Convert.ToInt32(cmd.ExecuteScalar()); //int idCabania = Convert.ToInt32(cmd.ExecuteScalar()); //Recupero Id de a cabania insertada det.Res.Id = res.Id; string sql2 = "INSERT INTO DETALLE_RESERVA (res_id,cab_id,precio,subtotal,fecha_desde,fecha_hasta,cant_dias,facturada) values (@ResId, @CabId,@Precio,@Subtotal,@FechaDesde,@FechaHasta,@CantDias,@Facturada); SELECT @@Identity as ID;"; cmd.CommandText = sql2; cmd.Parameters.AddWithValue("@ResId", det.Res.Id); cmd.Parameters.AddWithValue("@CabId", det.Cab.IdCabania); cmd.Parameters.AddWithValue("@Precio", det.Precio); cmd.Parameters.AddWithValue("@Subtotal", det.Subtotal); cmd.Parameters.AddWithValue("@FechaDesde", det.FechaDesde); cmd.Parameters.AddWithValue("@FechaHasta", det.FechaHasta); cmd.Parameters.AddWithValue("@CantDias", det.CantDias); cmd.Parameters.AddWithValue("@Facturada", det.Facturada); det.Id = Convert.ToInt32(cmd.ExecuteScalar()); tran.Commit(); //cabania.IdCabania = idCabania; //Seteo Id de la cabania insertada } catch (SqlException ex) { if (cn.State == ConnectionState.Open) tran.Rollback(); //Vuelvo atras los cambios throw new ApplicationException("Error al guardar la cabaña." + ex.Message); } finally { if (cn.State == ConnectionState.Open) cn.Close(); } }
protected void BtnNext_Click(object sender, EventArgs e) { try { con = new SqlConnection("integrated security=sspi;Server=.;Database=Jobs"); con.Open(); if (txtUname.Text == "" || txtPwd.Text=="") { lblmsg.Text = "sorry pls enter the required fileds"; } else { cmd = new SqlCommand("select count(*) from users where uname = @uname", con); cmd.Parameters.Add("@uname", SqlDbType.VarChar, 10).Value = txtUname.Text; int cnt = (int)cmd.ExecuteScalar(); if (cnt == 1) { lblmsg.Text = "Sorry! Username is already present. Try another name!"; return; } cmd.CommandText = "select count(*) from users where email = @email"; cmd.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = txtEmail.Text; cnt = (int)cmd.ExecuteScalar(); if (cnt == 1) { lblmsg.Text = "Sorry! Email address is already present."; return; } //cmd = new SqlCommand("insert into Users values(@p1,@p2,@p3,@p4,@p5,@p6,@p7)", con); //cmd.Parameters.Add(new SqlParameter("@p1", txtUname.Text)); //cmd.Parameters.Add(new SqlParameter("@p2", txtPwd.Text)); //cmd.Parameters.Add(new SqlParameter("@p4", dt)); //cmd.Parameters.Add(new SqlParameter("@p3", txtEmail.Text)); //cmd.Parameters.Add(new SqlParameter("@p6", txtAddress.Text)); //cmd.Parameters.Add(new SqlParameter("@p7", txtPhone.Text)); //cmd.Parameters.Add(new SqlParameter("@p5", ddlUtype.SelectedItem.Text)); //cmd.ExecuteNonQuery(); //con.Close(); //hPwd.Text = txtPwd.Text; hPwd.Text = txtPwd.Text; MultiView1.ActiveViewIndex = ddlUtype.SelectedIndex + 1; } } catch (Exception ex) { lblmsg.Text = "Error :" + ex.Message; } finally { con.Close(); } }
static void Main(string[] args) { var time= new DateTime(); string connectionString = GetConnectionString(); // Open a connection to the AdventureWorks database. using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Perform an initial count on the destination table. SqlCommand commandRowCount = new SqlCommand( "SELECT COUNT(*) FROM " + "dbo.BulkCopyDemoMatchingColumns;", connection); long countStart = System.Convert.ToInt32( commandRowCount.ExecuteScalar()); Console.WriteLine("Starting row count = {0}", countStart); // Create a table with some rows. DataTable newProducts = MakeTable(); // Create the SqlBulkCopy object. // Note that the column positions in the source DataTable // match the column positions in the destination table so // there is no need to map columns. using (var bulkCopy = new System.Data.SqlClient.SqlBulkCopy(connection)) { bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"; try { // Write from the source to the destination. var b = DateTime.Now.Second; bulkCopy.WriteToServer(newProducts); var a = DateTime.Now.Second; Console.WriteLine("bat dau:"+b); Console.WriteLine("Tổng thời gian Lưu:"+a); } catch (Exception ex) { Console.WriteLine(ex.Message); } } // Perform a final count on the destination // table to see how many rows were added. long countEnd = System.Convert.ToInt32( commandRowCount.ExecuteScalar()); Console.WriteLine("Ending row count = {0}", countEnd); Console.WriteLine("{0} rows were added.", countEnd - countStart); Console.WriteLine("Press Enter to finish."); Console.ReadLine(); } }
private void button1_Click(object sender, EventArgs e) { //必要信息填写验证 if (textBoxXINGZHI.Text == "" || textBoxBUMEN.Text == "" || textBoxWEITUOREN.Text == "" ) { MessageBox.Show("必要信息填写不完全"); } else { try { //申请估价编号算法,从新写,你妈的 SqlConnection conn = new SqlConnection(Jingtai.ConnectionString); conn.Open();//打开链接 //创建命令对象 SqlCommand cmd = null; //创建语句字符串 string sql = null; //到 table_ku 中获取指定年份的报告编号最大的数字和ID int baogaohao; sql = @"select MAX(报告编号) from Table_Ku where 报告年份='" + textBoxNIAN.Text + "'"; cmd = new SqlCommand(sql, conn); label3.Text = cmd.ExecuteScalar().ToString(); baogaohao = int.Parse(cmd.ExecuteScalar().ToString()); //得到最大的报告号 baogaohao++; sql = @"INSERT INTO Table_Ku (报告编号申请人,报告性质,相关部门,委托人,报告年份,报告编号,备注,编号申请时间) VALUES ('" + label2.Text + "','" + textBoxXINGZHI.Text + "','" + textBoxBUMEN.Text + "','" + textBoxWEITUOREN.Text + "','" + textBoxNIAN.Text + "','" + baogaohao + "','" + textBoxBEIZHU.Text + "','" + DateTime.Now + "')"; cmd = new SqlCommand(sql, conn); cmd.ExecuteNonQuery(); sql = @"select id from Table_Ku where 报告年份='" + textBoxNIAN.Text + "' and 报告编号='" + baogaohao.ToString() + "'"; cmd = new SqlCommand(sql, conn); int myid = int.Parse(cmd.ExecuteScalar().ToString()); Jingtai.myid = myid; conn.Close();//关闭连接 Close(); } catch(Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show("fenpeiyichang"); } } }
public int ktra(string sql) { SqlConnection conn = new SqlConnection(kn); SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); cmd.ExecuteScalar(); int i =(int)cmd.ExecuteScalar(); conn.Close(); return i; }
protected void Page_Load(object sender, EventArgs e) { if ((Session["SCSLogin"] != null) & (Session["SCSDate"] != null)) { if ((DateTime)Session["SCSDate"] <= DateTime.Now) Response.Redirect("Default.aspx"); login = (string)Session["SCSLogin"]; expDate = ((DateTime)Session["SCSDate"]).ToString(); Response.Write("<div align=center> В системе как: " + login + "<BR> В системе до: " + expDate + "<BR></div>"); Session["SCSDate"] = DateTime.Now.AddMinutes(10); Title = Title + " : " + login; } else Response.Redirect("Default.aspx"); string constr = WebConfigurationManager.ConnectionStrings["SCSDataBase"].ConnectionString; SqlConnection con = new SqlConnection(constr); try { con.Open(); SqlCommand cmd = new SqlCommand("exec ShowNewMessages @lg", con); cmd.Parameters.Add("@lg", login); SqlDataReader dr = cmd.ExecuteReader(); gvMessageViewer.DataSource = dr; gvMessageViewer.DataBind(); dr.Close(); for (int i = 0; i < gvMessageViewer.Rows.Count; i++) { string mes = gvMessageViewer.Rows[i].Cells[2].Text; if (mes.StartsWith("[REQUEST MESSAGE]") == true) { gvMessageViewer.Rows[i].Cells[2].Text = "[запрос]"; mes = mes.Replace("[REQUEST MESSAGE]", ""); cmd.CommandText = "exec getUserAccess @lg"; int acc = (int)cmd.ExecuteScalar(); if (acc == 4) { Response.Write("<div align=center>"); Response.Write("<a href=" + mes + "> подтвердить " + gvMessageViewer.Rows[i].Cells[1].Text + "</a>"); Response.Write("<BR>"); Response.Write("</div>"); } } } cmd.CommandText = "exec NewMessagesReadedAlready @lg"; cmd.ExecuteScalar(); } catch (Exception err) { Response.Write(err.Message); } finally { con.Close(); } }