Insert numerical (decimal) data from textbox values

后端 未结 2 954
[愿得一人]
[愿得一人] 2021-01-26 12:01

I am confused by the following issue;

I have a C# (WindowsForms) application which I connect to a SQL Server DB and have no problem to INSERT, SELECT, UPDATE... until I

2条回答
  •  Happy的楠姐
    2021-01-26 12:20

    First of all, Always use using when dealing with SqlConnection and SqlCommand and all other classes that implements IDisposable just read more about it..

    Second thing, Always use parameters with SqlCommand and never pass the values as a string to the sql string. This is a serious security issue. In addition to that parameters makes your code human friendly!

    // Always use (using) when dealing with Sql Connections and Commands
    using (sqlConnection conn = new SqlConnection())
    {
        conn.Open();
    
        using (SqlCommand newCmd = new SqlCommand(conn))
        {
            newCmd.CommandType = CommandType.Text;
    
            newCmd.CommandText = 
                  @"INSERT INTO tblContracts (CreatedById, CreationDate, EmployeeId, Role, ContractType, StartDate, EndDate, Agency, LineManager, ReportTo, CostCenter, FunctionEng, AtrNo, AtrDate, PrNo, PrDate, PoNo, PoDate, Comments, Duration, WorkRatePercent, Currency, HourlyRate, Value) 
                  VALUES (@UserID, @CreationDate, @EmployeeID, @Role.....etc)";
    
            // for security reasons (Sql Injection attacks) always use parameters
            newCmd.Parameters.Add("@UserID", SqlDbType.NVarChar, 50)
                 .Value = connectedUser.getUserId();
    
            newCmd.Parameters.Add("@CreationDate", SqlDbType.DateTime)
                 .Value = DateTime.Now;
    
            // To add a decimal value from TextBox
            newCmd.Parameters.Add("@SomeValue", SqlDbType.Decimal)
                 .Value = System.Convert.ToDecimal(txtValueTextBox.Text);
    
            // complete the rest of the parameters
            // ........
    
            newCmd.ExecuteNonQuery();
    
            MessageBox.Show("Contract has been successfully created", "Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
    

提交回复
热议问题