简体   繁体   English

如何使用vb.net插入Visual Studio数据库

[英]How to insert into Visual Studio Database using vb.net

I'm using Visual Studio 2015 and I can't get my code to insert data into Visual Studio database. 我正在使用Visual Studio 2015,但无法获取将数据插入Visual Studio数据库的代码。 There are no error and the aspx page run fine but the data is not being write. 没有错误,aspx页运行正常,但未写入数据。 Here is my code: 这是我的代码:

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

I be greatly appreciated if you can point out my error. 如果您能指出我的错误,我们将不胜感激。

As Plutonix says: ExecuteReader is for reading the results of a SELECT query a row at a time. 正如Plutonix所说:ExecuteReader用于一次读取一行SELECT查询的结果。 You want ExecuteNonQuery to run an INSERT query. 您希望ExecuteNonQuery运行INSERT查询。

Also, NEVER use concatenation to build a query with user input. 同样,从不使用串联来建立带有用户输入的查询。 In some cases you might find it useful to build queries from pre-defined strings, but with random input, a person with bad intentions could wipe out your entire database with the right input. 在某些情况下,您可能会发现从预定义的字符串中构建查询很有用,但是如果输入是随机的,那么恶意的人可能会用正确的输入抹掉整个数据库。 Use Parameters !! 使用参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM