2015-12-08 79 views
0

我正在使用Visual Studio 2015,我不能讓我的代碼插入數據到Visual Studio數據庫。沒有錯誤,aspx頁面運行正常,但數據不在寫入。這裏是我的代碼:如何使用vb.net插入到Visual Studio數據庫

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 

我非常感謝,如果你能指出我的錯誤。

+2

不要使用ExecuteReader來插入數據;不要concat SQL,使用參數,爲了所有的聖潔,不要存儲未加密的信用卡號碼(如果有的話),當然不是Ints。並處理你的數據庫對象 – Plutonix

回答

0

正如Plutonix所說:ExecuteReader用於讀取每次SELECT行查詢的結果。你想ExecuteNonQuery運行一個INSERT查詢。

另外,從不使用連接來構建帶有用戶輸入的查詢。在某些情況下,您可能會發現從預定義的字符串構建查詢很有用,但隨機輸入時,意圖不好的人可能會用正確的輸入清除整個數據庫。使用Parameters

相關問題