Insert date into SQL Server database through vb.net -
dim salesinsert new sqlcommand("insert tbl_sales (sale_id, transaction_no, customer_id, item_id, amount, date) values(" _ & salesidmax + 1 & "," & transaction_label.text & "," & 1 & "," & label4.text & "," & textbox1.text & _ "," & datetimepicker1.value.date & ")", sqlcon) sqlcon.open() salesinsert.executenonquery() sqlcon.close() salesinsert = nothing
i have code. works fine, problem date. reason inserts same date every time: "1/1/1900".
when debugged code see sql command text fine , date fine , executed in sql query , fine.
but in vb doesn't.
i not know why not working.
please can have suggestions fix it.
if use parameterized queries avoid problems representing dates strings.
you can use sql parameters (i had guess @ database column data types) query this:
dim salesinsert new sqlcommand("insert 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 {.parametername = "@saleid", .sqldbtype = sqldbtype.int, .value = salesidmax + 1}) salesinsert.parameters.add(new sqlparameter {.parametername = "@transactionno", .sqldbtype = sqldbtype.nvarchar, .size = 20, .value = transaction_label.text}) salesinsert.parameters.add(new sqlparameter {.parametername = "@customerid", .sqldbtype = sqldbtype.int, .value = 1}) salesinsert.parameters.add(new sqlparameter {.parametername = "@itemid", .sqldbtype = sqldbtype.nvarchar, .size = 20, .value = label4.text}) salesinsert.parameters.add(new sqlparameter {.parametername = "@amount", .sqldbtype = sqldbtype.decimal, .value = cdec(textbox1.text)}) salesinsert.parameters.add(new sqlparameter {.parametername = "@date", .sqldbtype = sqldbtype.datetime, .value = datetimepicker1.value}) sqlcon.open() salesinsert.executenonquery() sqlcon.close() salesinsert.dispose()
- i escaped column names square brackets - avoids problems using sql reserved keywords column names. easier escape column names.
- you should not set
salesinsert = nothing
- instead, usesalesinsert.dispose()
cleans unmanaged resources properly. - you need change each
.sqldbtype
(and.size
strings) match datatypes of database columns. decimal values ought have.scale
,.precision
defined too. - the controls descriptive names -
textbox1
not suggest have amount in it. - the values should validated before running query, e.g. can amount text converted decimal , sensible value.
Comments
Post a Comment