我对 SQL 命令参数完全陌生(我昨天已经简要解释了这个概念,可能不明白),通常是 OOP,但我喜欢它:D
这是我昨天的问题的链接;) 伙计们确实提供了帮助,但是我现在很难在我的应用程序中实现这一点
我实际上已经构建了一个示例:
表单“formConnection.cs”包含 2 个用户输入“comboBoxEmployeeId”(selectedvalue 是一个 int)+“txtDuration”(值是一个小数),点击“btnInsert”我会处理这个:`
sqlDbOperations sqlDbOp = new sqlDbOperations();` public void btnInsert_Click(object sender, EventArgs e) { //Create new contract var contract = new contract{ employeeId = Convert.ToInt32(this.comboBoxEmployeeName.SelectedValue), duration = Convert.ToDecimal(this.txtDuration.Text) }; //Insert command to Db sqlDbOp.insertContract(); MessageBox.Show("Done"); }
类“合同.cs”
class contract { public int employeeId { get; set; } public decimal duration { get; set; } }
类“sqlDbOperations.cs”
public class sqlDbOperations { //连接字符串 //SqlConnection myConnection = new SqlConnection("ATLELAG786576\SQLEXPRESS;Initial Catalog=TEST;Integrated Security=False;Connect Timeout=30;User Instance=False;User ID=basicuser;Password=basicpw" ); SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["EngAdminSqlDbConnectionString"].ConnectionString);
//Connection open //SqlConnection.Open() is a void function and does not return an error but throws an exception so remember to put it in a try/catch brace //Rather than having the program explode in front of the user public void openConnection() { //Connection open try { myConnection.Open(); } catch (Exception e) { Console.WriteLine(e.ToString()); MessageBox.Show(e.ToString()); } } //Connection close //Try/catch because like SqlConnection.Open() it does not return errors but throws an exception instead public void closeConnection() { try { myConnection.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } contract contract = new contract(); public void insertContract() { //Open openConnection(); //Command SqlCommand myCommand = new SqlCommand("INSERT INTO tblContracts (EmployeeId, Duration) VALUES (@employeeId, @contractDuration)", myConnection); //Get values from form formConnection formInput = new formConnection(); //Add parameters myCommand.Parameters.AddWithValue("@employeeId", contract.employeeId); myCommand.Parameters.AddWithValue("@contractDuration", contract.duration); //Execute myCommand.ExecuteNonQuery(); //Close closeConnection(); } }
这不起作用 - 当我在我的 txtDuration 文本框中输入像 2.7 这样的“十进制”值时,我仍然收到一条消息:
System.FormatException:Le format de la chaîne d'entrée est 不正确。= "输入字符串格式不正确" à System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)à System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt)à System .Convert.ToDecimal(String value) à SQLStatementParameters.formConnection.btnInsert_Click(Object sender, EventArgs e) dans D:\C#\Projects\SQLStatementParameters\SQLStatementParameters\formConnection.cs:ligne 26à System.Windows.Forms.Control.OnClick(事件参数 e)"......
- 数据库中没有存储任何内容(好像这些值没有从表单传输到对象“合同”,然后传输到执行 INSERT 的方法),我有一条新记录,但它都是空的
我究竟做错了什么?感谢您的帮助!
布莱斯