Click here to Skip to main content
15,900,110 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
query = "insert into stock_sales_system.customer() values('" & txtCustomerName.Text & "', '" & txtAddress.Text & "', '" & cbxCity.Text & "', '" & txtTelephone.Text & "', '" & dtpDate.Value & "', '" & txtDescription.Text & "', '" & 0 & "', '" & 0 & "')"


What I have tried:

i have changed the format of the DateTimePicker to custom 'yyyy-MM-dd' but i face the same problem
Posted
Updated 24-Apr-20 3:34am
v2

1 solution

C#
using (SqlCommand cmd = new SqlCommand(connection))
{
   cmd.CommandText = "INSERT INTO stock_sales_system.customer (name, address, city, telephone, datefield, description, unknownfield1, unknonwnfield2) VALUES (@name, @address, @city, @telephone, @date, @description, @field1, @field2)";
   cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = txtCustomerName.Text;
   cmd.Parameters.Add("@address", SqlDbType.NVarChar).Value = txtAddress.Text;
   cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = cbxCity.Text;
   cmd.Parameters.Add("@telephone", SqlDbType.NVarChar).Value = txtTelephone.Text;
   cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = dtpDate.Value;
   cmd.Parameters.Add("@description", SqlDbType.NVarChar).Value = txtDescription.Text;
   cmd.Parameters.Add("@field1", SqlDbType.Int).Value = 0;
   cmd.Parameters.Add("@field2", SqlDbType.Int).Value = 0;
   int result = cmd.ExecuteNonQuery();
}


Here you will have to provide proper column names as I had to guess them since you did not show them.

The bad habits you should lose asap:

  • building SQL queries by concatenating strings obtained from use inputs; this is a no-go as this leaves your code wide open to SQL injection attacks.
  • not providing column names in your SQL queries.
  • treating everything as strings. This is what you do when you enclose every value between single quotes. Please always use proper types, and make sure to follow proper syntax for each of them. Using query parameters discharge you from putting any quote in the query, anyway.
 
Share this answer
 
Comments
MadMyche 24-Apr-20 10:02am    
+5... this is the solution that I would have written.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900