我使用的是Visual Studio 2015,但我无法获取将代码插入Visual Studio数据库的代码。没有错误,aspx页面运行正常,但数据没有写入。这是我的代码:
Dim strConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("Project1ConnectionString").ConnectionString
Dim drCart As SqlDataReader
Dim strSQLStatement As String
Dim cmdSQL As SqlCommand
strSQLStatement = "SELECT * FROM OrderHead"
Dim conn As New SqlConnection(strConnectionString)
cmdSQL = New SqlCommand(strSQLStatement, conn)
conn.Open()
drCart = cmdSQL.ExecuteReader()
Dim ExpCard = CMonth.Text + CYear.Text
Dim Fname = FristTxt.Text
Dim Lname = LastTxt.Text
Dim Address1 = AddTxt1.Text
Dim Address2 = AddTxt2.Text
Dim City = CityTxt.Text
Dim State = StateDList.Text
Dim ZipCode = ZipTxt.Text
Dim PhoneNum = NumTxt.Text
Dim CreditNum = CNumber.Text
Dim CreditType = CtypeList.Text
If drCart.Read() Then
Dim strSQLStatement2 = "Insert into OrderHead (FirstName, LastName, StreetAddress, City, State, Zip, PhoneNumber, CreditCard, CreditType, ExpDate, StreetAddress2) VALUES (" & Trim(Fname) &
", " & Trim(Lname) & ", " & Trim(Address1) & ", " & Trim(City) & ", " & Trim(State) &
", " & CInt(ZipCode) & ", " & CInt(PhoneNum) & ", " & CInt(CreditNum) & ", " & Trim(CreditType) &
", " & CInt(ExpCard) & ", " & Trim(Address2) & "')"
Dim conn2 As New SqlConnection(strConnectionString)
conn2.Open()
Dim cmdSQL2 = New SqlCommand(strSQLStatement2, conn2)
drCart = cmdSQL2.ExecuteReader()
conn2.Close()
End If
如果你能指出我的错误,我将不胜感激。
答案 0 :(得分:0)
正如Plutonix所说:ExecuteReader用于一次读取一行SELECT查询的结果。您希望ExecuteNonQuery运行INSERT查询。
此外,永远不要使用串联来构建具有用户输入的查询。在某些情况下,您可能会发现从预定义的字符串构建查询很有用,但是随机输入,意图不好的人可能会使用正确的输入消灭整个数据库。使用Parameters !!