ODBC connection to MySQL won't add values
I'm trying to insert values from my asp.net application into my MySQL database.
On the register page people can fill in Name
and Pass
and press submit.
Public Function InsertMember(ByVal objMember As Member) As Boolean
myconn.Open()
Dim cmd As New OdbcCommand("INSERT INTO member(Name, Pass) VALUES (@Name,@Pass)", myconn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("Name", OdbcType.VarChar).Value = objMember.Name
cmd.Parameters.Add("Pass", OdbcType.VarChar).Value = objMember.Pass
cmd.ExecuteNonQuery()
cmd.Dispose()
开发者_StackOverflowcmd = Nothing
myconn.Close()
myconn.Dispose()
Return True
End Function
But all this does is add NULL values into my database.
Any clues on what I'm doing wrong?
How about switching convention to use ?
and parameter names matching the column names?
Perhaps consider switching to AddWithValue()
if you can.
From the MSDN OdbcParameterCollection.Add
Method
Dim insertSQL As String = "INSERT INTO member(Name, Pass) VALUES (?,?)"
Dim cmd As New OdbcCommand(insertSQL, myconn)
'cmd.Parameters.Add("Name", OdbcType.VarChar).Value = objMember.Name '
cmd.Parameters.AddWithValue("Name", objMember.Name)
cmd.Parameters.AddWithValue("Pass", objMember.Pass)
'Note that with ODBC Command, the ORDER you add to the parameters collection
'matters most. The names of your params don't matter.
I suspect the ?
placeholders will be filled with the values in order as they're added to the Parameters collection (from another question/answer).
Here is a link to an article that should solve your problem. Basically, replace the @ characters with ? characters instead.
http://forums.asp.net/t/1283161.aspx
The OP in that forum was having problems with null values being inserted just like you. The solution was to modify the code like so:
Dim cmd As New OdbcCommand("INSERT INTO member(Name, Pass) VALUES (?Name,?Pass)", myconn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("?Name", objMember.Name)
cmd.Parameters.Add("?Pass", objMember.Pass)
cmd.ExecuteNonQuery()
If you want to specify the value type for the field, you can do it like you had but you should add the length afterwards like so:
cmd.Parameters.Add("?Name", OdbcType.VarChar, 30).Value = objMember.Name
I hope that helps.
精彩评论