0

在运行下面的代码之后..

Dim p As String = sqlcomm1.ExecuteNonQuery() 

字符串 p 正在加载-1,但查询在 sqlserver 中给出了正确的输出

Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click

    Dim customerID, billno, billdate, Nettotal As String
    customerID = DropDownList1.SelectedValue
    billno = TextBox1.Text
    billdate = TextBox4.Text
    Nettotal = TextBox10.Text

    Dim sqlcon As New SqlConnection("Data Source=192.168.0.22\SQLEXPRESS;Initial Catalog=Sales_oct_3;Persist Security Info=True;User ID=a;Password=so")


    If sqlcon.State = ConnectionState.Open Then
        sqlcon.Close()
    End If
    sqlcon.Open()
    Dim strcommand As String
    Dim strcommd1 As String
    strcommand = "Insert into tinsales(customerID,Billno,Billdate,Nettotal) values ('" + customerID + "','" + billno + "','" + billdate + "','" + Nettotal + "')"
    strcommd1 = "select max(salesId) as salesID from [tinsales]"
    Dim sqlcomm As New SqlCommand(strcommand, sqlcon)
    Dim sqlcomm1 As New SqlCommand(strcommd1, sqlcon)

    Dim o As String = sqlcomm.ExecuteNonQuery()
    Dim p As String = sqlcomm1.ExecuteNonQuery()

Dim total As Double = 0 For Each gvr As GridViewRow In GridView1.Rows Dim temp As Double = Convert.ToDouble(gvr.Cells(4).Text) total += temp Next TextBox10.Text = total.ToString()

4

2 回答 2

0

不要连接字符串来构建查询,您可以进行 sql 注入。使用 sql 参数。

要获取最后插入的标识值,请不要使用

select max(salesId) as salesID from [tinsales]

您可以在一个命令中插入和选择它。因此使用SCOPE_IDENTITYand ExecuteScalar

Using con = New SqlConnection("Data Source=192.168.0.22\SQLEXPRESS;Initial Catalog=Sales_oct_3;Persist Security Info=True;User ID=sa;Password=sofker")
    Dim sql = "INSERT INTO tinsales(customerID,Billno,Billdate,Nettotal) VALUES(@customerID,@billno,@billdat,@Nettotal);" & _
              "SELECT CAST(SCOPE_IDENTITY AS INT);"
    Using cmd = New SqlCommand(sql, con)
        cmd.Parameters.AddWithValue("@customerID", customerID)
        cmd.Parameters.AddWithValue("@billno", billno)
        cmd.Parameters.AddWithValue("@billdate", billdate)
        cmd.Parameters.AddWithValue("@Nettotal", Nettotal)
        con.Open()
        Dim newPrimaryKey As Int32 = DirectCast(cmd.ExecuteScalar(), Int32)
    End Using
End Using
于 2013-10-24T11:00:04.993 回答
0

更改ExecuteNonQueryExecuteScalar

Dim p As String = sqlcomm1.ExecuteScalar()

ExecuteScalar执行查询,并返回查询返回的结果集中第一行的第一列。其他列或行将被忽略。

另外我建议更改您的内联查询以使用参数化命令,因为它更安全(防止 SQL 注入攻击)并且类型安全(在传递时非常有用DateTime

strcommand = "Insert into tinsales(customerID, Billno, Billdate, Nettotal) values (@customerId, @billno, @billdate, @nettotal)"

Dim sqlcomm As New SqlCommand(strcommand, sqlcon)
sqlcomm.Parameters.AddWithValue("@customerId", customerID)
sqlcomm.Parameters.AddWithValue("@billno", billno)
sqlcomm.Parameters.AddWithValue("@billdate", billdate)
sqlcomm.Parameters.AddWithValue("@nettotal", Nettotal)
于 2013-10-24T10:54:17.813 回答