I have an INSERT code where the variable s = 4. Help would be pretty appreciated.
con.Open()
Dim cmd As New SqlCommand(\"INSERT INTO Employee VALUES
The missing closing parens is one of the lesser problems in what you have:
A better way to create the SQL for a long query which addresses 1, 2 and 3 is something like this:
' an XML literal
Dim SQL =
INSERT INTO Employee
(FirstName, LastName, SocSecNum, BirthDate,
Address, Gender
...)
VALUES
(@firstN, @lastN, @SSN ... )
Using cmd As New SqlCommand(sql.Value, con)
...
cmd.Parameters.AddWithValue("@firstN", txtfname.Text)
cmd.Parameters.AddWithValue("@lastN", txtlname.Text)
...
cmd.ExecuteNonQuery()
...
End Using ' disposes of the object when done
Even though INSERT INTO tablename VALUES ...
is legal syntax, it assumes that your db will have the columns in the some order and that it will not change as you alter the db. The above method explicitly maps parameters to columns based on the order of the columns and parameter placeholders. The names ("@firstN") make it easy for you to see which value you are working with.
Using an XML literal will allow you to layout the text however it is most readable to you, but even a string literal can be easier to read and maintain than concatenating:
Dim strSQL As String = "INSERT INTO Employee (FirstName, LastName, SocSecNum, " _
& "BirthDate, Address, Gender ..." _
& " VALUES (@p1, @p2...)"
Using either method, the missing parens in the OP would have been much more obvious and less likely to have happened at all. Next, some columns appear to be numeric such as Salary and BirthDate, so SQL such as this may be wrong:
... & "','" & txtbdate.Text & "','" & txtsalary.Text & "','" ...
Placing ticks around the value assures that you are passing a String to the dbLayer. If Salary is a numeric column and DateOfBirth is a date column -- as they should be -- then you may well get a data type mismatch error. Parameters make it easier to pass the correct data type because you can see what you are working with:
cmd.Parameters.AddWithValue("@DOB", CDate(txtbdate.Text))
cmd.Parameters.AddWithValue("@Salary", CDec(txtsalary.Text))
(Note, when using OleDB, parameters are simply ordinal so be sure to AddWithValue
in the same order as specified in the SQL). Passing the wrong datatype can cause the dblayer to make some assumptions, to avoid this you can do it the long way:
cmd.Parameters.Add("@firstN", SqlDbType.VarChar, 32) ' 32 = column def
cmd.Parameters("@firstN").Value = txtfname.Text
One more issue is that the code does not seem to perform any data validation. What if they type "I like pie" as the Salary? Or enter "02/31/1986" (mm/dd) for BirthDate? Your code will crash deep into this procedure. So data validation using things like DateTime.TryParse
and Integer.TryParse
on the user input should have (and may have) taken place much further upstream.