我试图弄清楚如何使用命令参数通过SQL语句传递值,因为连接根本不起作用,但我遇到了一个奇怪的问题,我找不到任何关于它的信息。
每当调用SQL语句时,参数的名称(如@ Address1)将被放入我的数据库而不是参数的值。
这是我的SQL语句,命令和连接代码:
Private Function qDBase()
con.ConnectionString = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source=.\pos408_w4_Team_B_Database.accdb;Persist Security Info=False" ' database should be located with the .exe file so that it can be detected and connected to
Try 'Make sure we also wrap connection statement in try in case something fails there
con.Open()
Try ' Wrap each query in a try/catch so that if it fails it will not fail silently due to code in Button1_Click
' Always do Customer_Index first, the primary key here is a secondary key in Account_Index, via one-to-many relationship, and unless the corresponding value can be loaced in Customer_Index it will fail to insert the data
qStr = "Insert Into `Customer_Index` Values('@Soc2','@FName','@MInitial','@LName','@DriverL','@Address1','@Address2','@City','@State','@Zip2','@Phone2','@Email');"
' Create and append parameters list
com.Parameters.AddWithValue("Soc2", Soc2)
com.Parameters.AddWithValue("FName", FName)
com.Parameters.AddWithValue("MInitial", MInitial)
com.Parameters.AddWithValue("LName", LName)
com.Parameters.AddWithValue("DriverL", DriverL)
com.Parameters.AddWithValue("Address1", Address1)
com.Parameters.AddWithValue("Address2", Address2)
com.Parameters.AddWithValue("City", City)
com.Parameters.AddWithValue("State", State)
com.Parameters.AddWithValue("Zip2", Zip2)
com.Parameters.AddWithValue("Phone2", Phone2)
com.Parameters.AddWithValue("Email", Email)
com.CommandText = qStr ' Set command value to qStr
com.Connection = con ' Set command connection
com.ExecuteNonQuery() ' Execute the command
qSuccesses += 1
Catch ex As Exception
MsgBox(ex) ' Show thrown exception to user
End Try
'Try
'qStr = "Insert Into `Account_Index` Values('" & Account & "','" & Soc & "','" & AccountType & "');"
'com.CommandText = qStr ' Set command value to qStr
'com.ExecuteNonQuery() ' Execute the command
' qSuccesses += 1
' Catch ex As Exception
' MsgBox(ex) ' Show thrown exception to user
' End Try
Catch ex As Exception
MsgBox(ex) ' Show thrown exception to user
Return False ' REturn prematurely because connection could not be made, no point going any further
End Try
If (qSuccesses = 1) Then ' If both try's work
qSuccesses = 0 ' reset to zero
Return True ' return true
Else ' If one or both try's fail
qSuccesses = 0 'reset to zero
Return False ' return false
End If
End Function
表单加载时初始化时应发送的值:
Soc2 = "123-45-6789"
FName = "Test"
MInitial = "D"
LName = "Test"
DriverL = "Test"
Address1 = "123 Test Rd"
Address2 = " "
City = "Denver"
State = "CO"
Zip2 = "12345-6789"
Phone2 = "(123)456-7890"
Email = "Test@Test.com"
然后是Access 2010数据库中的输出:
@Soc2 @FName @Minitial @LName @DriverL @ Address1 @ Address2 @City @State @ Zip2 @ Phone2 @Email
AddWithValue不能正常工作吗?
答案 0 :(得分:0)
我讨厌发生这种情况,在发布问题后计算出几分钟。我不应该在SQL语句中使用撇号。刚刚决定尝试用它来处理它的问题,这次它运作得很好。