locked
FAQs:怎样用VB.NET 使用参数查询数据库? RRS feed

答案

  • 代码示例:(SQL Server

    Imports System.Data.SqlClient

    Public Class Form1

        Private Sub Button1_Click(ByVal sender As System.Object, _

                            ByVal e As System.EventArgs) Handles Button1.Click

            Dim con As SqlConnection = New SqlConnection( _

                            "Data Source=.;Integrated Security=True;AttachDbFilename=D:\myDB.mdf")

            con.Open()

            Dim cmdText As String = _

                            "INSERT INTO Customer(UserName, [Password]) VALUES (@UserName,@Password)"

            Dim cmd As SqlCommand = New SqlCommand(cmdText, con)

            With cmd.Parameters

                .Add(New SqlParameter("@UserName", txtUserName.Text))

                .Add(New SqlParameter("@Password", txtPassword.Text))

            End With

            cmd.ExecuteNonQuery()

            con.Close()

            con = Nothing

        End Sub

    End Class

     

    代码示例:(MS ACCESS)

    Imports System.Data.OleDb

    Public Class Form1

        Private Sub Button1_Click(ByVal sender As System.Object, _

                            ByVal e As System.EventArgs) Handles Button1.Click

            Dim con As OleDbConnection = New OleDbConnection( _

                            "Provider=Microsoft.jet.oledb.4.0;data source=D:\myDB.mdb")

            con.Open()

            Dim cmdText As String = "INSERT INTO Customer(UserName, [Password]) VALUES (?,?)"

            Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)

            cmd.CommandType = CommandType.Text ‘ The default is CommandType.Text

            With cmd.Parameters

                .Add("@p1", OleDbType.VarChar).Value = txtUserName.Text

                .Add("@p2", OleDbType.VarChar).Value = txtPassword.Text

            End With

            cmd.ExecuteNonQuery()

            con.Close()

            con = Nothing

        End Sub

    End Class

    详细资料:

    http://msdn.microsoft.com/zh-cn/library/system.data.oledb.oledbcommand.parameters.aspx

    http://support.microsoft.com/kb/310070
    如果您对我们的论坛在线支持服务有任何的意见或建议,请通过邮件告诉我们。
    MSDN 论坛好帮手 立刻免费下载  MSDN 论坛好帮手
    2011年3月3日 2:20