Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从文本框值插入数字(十进制)数据_C#_Sql_Insert_Numeric - Fatal编程技术网

C# 从文本框值插入数字(十进制)数据

C# 从文本框值插入数字(十进制)数据,c#,sql,insert,numeric,C#,Sql,Insert,Numeric,我对以下问题感到困惑 我有一个C#(WindowsForms)应用程序,我将其连接到SQL Server数据库,插入、选择、更新……都没有问题。。。直到我开始研究数字数据 此应用程序的目的是管理员工、他们的合同、工作率、合同期限、小时工资。。。用它做一些有趣的计算,没有什么神奇的 基本上,我需要在数据库中存储一些格式为“00000000”的值(十进制?双浮点?) 在我的数据库中,我将表中的所有列都设置为需要将这些“0000000”值设置为十进制 在我的表单中,我没有为文本框指定任何特定属性 要

我对以下问题感到困惑

我有一个C#(WindowsForms)应用程序,我将其连接到SQL Server数据库,插入、选择、更新……都没有问题。。。直到我开始研究数字数据

此应用程序的目的是管理员工、他们的合同、工作率、合同期限、小时工资。。。用它做一些有趣的计算,没有什么神奇的

基本上,我需要在数据库中存储一些格式为“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:Le format de la chaîne d'entrée est不正确=输入/输入字符串的格式不正确
§System.Number.StringToNumber(字符串str、NumberStyles选项、NumberBuffer&Number、NumberFormatInfo、布尔解析十进制)
§System.Number.ParseDecimal(字符串值、NumberStyles选项、NumberFormatInfo numfmt)
§System.Convert.ToDecimal(字符串值)


您有什么建议?

首先,在处理
SqlConnection
SqlCommand
以及实现
IDisposable
的所有其他类时,请务必使用
using

其次,始终将参数与
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)

另外(正如其他人已经指出的)使用命令参数

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

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

如果SQL语句是参数化SQL注入,那么它会更安全、可读性更强:我建议您创建一个契约类作为所有字段的容器,而不是一个具有20多个参数的方法。Cheers Filburt,图片上的例子很清楚:欢迎光临。另外,由于您是StackOverflow的新手,我想通知您,您可以通过勾选答案旁边的勾号来选择好答案并接受对您帮助最大的答案。在这个网站上,一个向上投票或一个被接受的答案都算作“谢谢”。谢谢奥利弗!我将继续这样做,谢谢你们所有人的宝贵帮助和建议!
newCmd.Parameters.AddWithValue("@EmployeeID", contract.EmployeeID);
newCmd.Parameters.AddWithValue("@Agency", contract.Agency);
newCmd.Parameters.AddWithValue("@Role", contract.Role);