插入文本框值中的数字(十进制)数据



我对以下问题感到困惑;

我有一个C#(WindowsForms)应用程序,我将其连接到SQL Server数据库,并且对INSERT、SELECT、UPDATE没有问题。。。直到我开始研究数字数据;

此应用程序的目的是管理员工、他们的合同、工作费率、合同期限、小时费率。。。并用它做一些有趣的计算,没有魔法

基本上,我需要在数据库中存储一些格式为"00000000"的值(十进制?双精度?浮点?)。

  • 在我的数据库中,我已经将我的表设置为所有需要将这些"0000000"值十进制的列

  • 在我的表单中,我没有为我的文本框指定任何特定的属性,

  • 为了插入,我使用了一种方法,我为其定义了十进制参数

    public void createNewContract(int employeeId, string agency, string role, string contractType, string startDate,
    string endDate, string lineManager, string reportTo, string costCenter, string functionEng, string atrNo, string atrDate, string prNo, string prDate,
    string poNo, string poDate, string comments, decimal duration, decimal workRatePercent, string currency, decimal hourlyRate, decimal value)
    {
    if (conn.State.ToString() == "Closed")
    {
    conn.Open();
    }
    SqlCommand newCmd = conn.CreateCommand();
    newCmd.Connection = 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 ('" + connectedUser.getUserId() + "','" + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + "','" + employeeId + "','" + role + "','" + contractType
    + "','" + startDate + "','" + endDate + "','" + agency + "','" + lineManager + "','" + reportTo + "','" + costCenter + "','" + functionEng + "','" + atrNo + "','" + atrDate + "','" + prNo
    + "','" + prDate + "','" + poNo + "','" + poDate + "','" + comments + "','" + duration + "','" + workRatePercent + "','" + currency + "','" + hourlyRate + "','" + value + "')";
    newCmd.ExecuteNonQuery();
    MessageBox.Show("Contract has been successfully created", "Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    

(通过这种方法,我只需要插入000000的持续时间(nb小时)、工作费率百分比、小时费率(货币)和价值(货币)

  • 为了捕获我的文本框值并通过我的方法"createNewContrat"发送它们,我尝试Convert.ToDecimal(this.txtDuration.Text)和许多其他对我来说似乎很好的东西,但我无法理解其中的机制,而且我肯定没有使用最实用/最聪明的解决方案

我一直收到以下错误;

System.FormatException:入口格式不正确=输入/输入字符串的格式不正确
àSystem.Number.StringToNumber

您有什么建议?

首先,在处理SqlConnectionSqlCommand时始终使用using,以及所有其他实现IDisposable的类

第二件事,始终将参数与SqlCommand一起使用,并且从不将值作为字符串传递给sql字符串。这是一个严重的安全问题。除此之外,参数还使您的代码人性化!

// 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);
}
}

这不是你问题的直接答案,但请(!)用这个替换这个丑陋的方法:

为您的合同创建一个类。这将使处理合同更加容易。如果您有几种方法以某种方式处理契约,那么在将属性添加到契约时,您将不必更改所有方法的几乎无穷无尽的参数列表。

public class Contract
{
public int EmployeeID { get; set; }
public string Agency { get; set; }
public string Role { get; set; }
... and so on
}

并将方法签名更改为

public void CreateNewContract(Contract contract)

从数据库加载合同的方法的头看起来像这个

public List<Contract> LoadAllContracts()
// Assuming contractID is the primary key
public Contract LoadContractByID(int contractID)

比返回1000个变量容易多了!

您可以使用创建新合同

var contract = new Contract {
EmployeeID = 22,
Agency = "unknown",
Role = "important", 
...
};

此外(正如其他人已经指出的那样)使用命令参数。

newCmd.Parameters.AddWithValue("@EmployeeID", contract.EmployeeID);
newCmd.Parameters.AddWithValue("@Agency", contract.Agency);
newCmd.Parameters.AddWithValue("@Role", contract.Role);

(HaLaBi的帖子展示了如何制定插入命令字符串。)

最新更新