-2

我是 VB.Net 的新手 我的旧 VB 6 代码是:

Set conn = my connection string
conn.open
Set ce = conn.Execute("select * from table where id = 1")
If ce.EOF Then conn.Execute ("insert into table set name = '" & Text1.Text & "'")

我想获取 sql 表字段,如果 eof 然后使用VB.NET添加记录。感谢帮助。

4

1 回答 1

3

您的旧 vb6 代码很糟糕:它容易受到 sql 注入的影响,而且效率极低,因为无需将结果返回给客户端。即使在 vb6 中,也没有任何借口。让我们通过 vb.net 迁移来解决这两个问题。您的新代码应如下所示:

Public Sub InsertName(ByVal Name As String)
    'This sql code will update your database in the same way as your original, but
    ' will do so faster because you only need to make one call to the database
    ' and you never need to read any data back to the client
    Dim sql As String = _
        "INSERT INTO Table (Name) " & _ 
           " SELECT @Name WHERE NOT EXISTS (select * from table where id = 1)"

    'The using blockwill make sure the connection is closed, even if an exception is thrown
    Using cn As New SqlConnection("My connection string"), _
          cmd As New SqlCommand(sql, cn)

        'Query parameters are the ONLY acceptable way to substitute data in your sql statements
        'NEVER use string concatenation. This is IMPORTANT
        'I have to guess at your column type here. Use the actual column type in your own code
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = Name

        cn.Open()
        cmd.ExecuteNonQuery()
    End Using
End Sub

然后像这样调用函数:

InsertName(Text1.Text)

请注意,我在这段代码中展示的大多数技术也是可用的,并且 vb6 中的最佳实践——即更好的 sql 和查询参数——即使你处理它们的方式在 vb6 中看起来不同。

于 2012-12-06T15:21:28.393 回答