If you always use parameterized queries then you will avoid problems with representing dates as strings.
You can use SQL parameters (I had to guess at the database column data types) for your query like this:
Dim salesinsert As New SqlCommand("INSERT INTO Tbl_Sales ([Sale_id], [Transaction_No], [Customer_id], [Item_id], [Amount], [Date])" &
" VALUES(@SaleId, @TransactionNo, @CustomerId, @ItemId, @Amount, @Date)", sqlcon)
salesinsert.Parameters.Add(New SqlParameter With {.ParameterName = "@SaleId", .SqlDbType = SqlDbType.Int, .Value = SalesIdMax + 1})
salesinsert.Parameters.Add(New SqlParameter With {.ParameterName = "@TransactionNo", .SqlDbType = SqlDbType.NVarChar, .Size = 20, .Value = Transaction_label.Text})
salesinsert.Parameters.Add(New SqlParameter With {.ParameterName = "@CustomerId", .SqlDbType = SqlDbType.Int, .Value = 1})
salesinsert.Parameters.Add(New SqlParameter With {.ParameterName = "@ItemId", .SqlDbType = SqlDbType.NVarChar, .Size = 20, .Value = Label4.Text})
salesinsert.Parameters.Add(New SqlParameter With {.ParameterName = "@Amount", .SqlDbType = SqlDbType.Decimal, .Value = CDec(TextBox1.Text)})
salesinsert.Parameters.Add(New SqlParameter With {.ParameterName = "@Date", .SqlDbType = SqlDbType.DateTime, .Value = DateTimePicker1.Value})
sqlcon.Open()
salesinsert.ExecuteNonQuery()
sqlcon.Close()
salesinsert.Dispose()
- I escaped the column names with square brackets - this avoids problems with using SQL reserved keywords as column names. It is easier to always escape the column names.
- You should not set
SALESINSERT = Nothing
- instead, use salesinsert.Dispose()
as this cleans up unmanaged resources properly.
- You need to change each
.SqlDbType
(and .Size
for strings) to match the datatypes of the database columns. The Decimal values ought to have the .Scale
and .Precision
defined too.
- The controls could do with descriptive names -
TextBox1
does not suggest that it will have an amount in it.
- The values should be validated before running the query, e.g. can the amount text be converted to a Decimal and is it a sensible value.