Well, often a lot of people jump in and say hey! - you should use parameters.
And they are right - but ONE big bonus feature? All the of the type conversions are done automatic. So in place of error prone strings? You wind up with this:
Using cmdSQL As New OdbcCommand("INSERT INTO Studies (Study, [Date], Patient) VALUES (@Study, @Date, @Patient",
New OdbcConnection(connectionString))
cmdSQL.Parameters.Add("@Study", OdbcType.Int).Value = 1411
cmdSQL.Parameters.Add("@Date", OdbcType.Date).Value = "2021-20-23"
cmdSQL.Parameters.Add("@patient", OdbcType.NVarChar).Value = "Fred"
cmdSQL.Connection.Open()
cmdSQL.ExecuteNonQuery()
cmdSQL.Dispose()
End Using
Now, of course your example was just that - an example. But, if you have strong typed vars, the you can get to do this:
cmdSQL.Parameters.Add("@Study", OdbcType.Int).Value = intStudy
cmdSQL.Parameters.Add("@Date", OdbcType.Date).Value = dtInvoiceDate
cmdSQL.Parameters.Add("@DateT", OdbcType.DateTime).Value = dtInvoiceTime
cmdSQL.Parameters.Add("@Customer", OdbcType.NVarChar).Value = strCompanyName
So, as you create the above, you can hit ctrl-d to duplicate the first line - so you not typing much. You just edit + change the parameter values. And you NEVER have to mess with quotes, no quotes, or date delimiters (assuming you declared the vars as date, or datetime.
I find saying good bye to mess string concatenations? Well, not only is this sql injection safe - but it just plain less messy to deal with. You use your clean variables, get strong data type checking, and you don't have to think or remember rules about quotes, no quotes or some kind of date format. It just clean code, and you just assign values.
So, it is a wee bit more code, but you actually not having to type the code (with ctrl-d to duplicate the first param line, then you just cursor around in the code and replace over the @parm and the .value. And you can work against a form data input like this:
cmdSQL.Parameters.Add("@Study", OdbcType.Int).Value = cboDrop.dataValue
cmdSQL.Parameters.Add("@Date", OdbcType.Date).Value = InvoiceDate.text
cmdSQL.Parameters.Add("@DateT", OdbcType.DateTime).Value = InvoiceTime.Text
cmdSQL.Parameters.Add("@Customer", OdbcType.NVarChar).Value = CompanyName.Text
So, once you introduce controls, then you are REALL in trouble if you use a string - since you can't just string in the controls and thus the string sql approach gets even worse and more difficult to write.
[Date]
? Or use / instead of - in date structure. - June72021-20-23
is not a valid date, so even when you do quoteDate
as June7 said, it'll certainly complain about that eventually, if not next. - madreflection[Date]
which didn't seem to help, but will try the / now. - AlainD