Dim p As String = sqlcomm1.ExecuteNonQuery() - 将-1加载到字符串中

时间:2013-10-24 10:52:44

标签: sql vb.net

在代码运行后运行..

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         对于GridView1.Rows中的每个gvr As GridViewRow             Dim temp As Double = Convert.ToDouble(gvr.Cells(4).Text)             总+ =临时         下一个         TextBox10.Text = total.ToString()

2 个答案:

答案 0 :(得分:0)

ExecuteNonQuery更改为ExecuteScalar

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)

答案 1 :(得分:0)

不要连接字符串来构建查询,而是打开sql注入。使用sql-parameters。

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

select max(salesId) as salesID from [tinsales]

您可以在一个命令中插入并选择它。因此,请使用SCOPE_IDENTITYExecuteScalar

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