传递参数以查询Access数据库

时间:2011-09-19 14:32:01

标签: vb.net ms-access

我正在使用以下代码并尝试按给定参数获取数据。我不知道如何将参数值传递给我的查询。

Dim con As New OleDb.OleDbConnection
    Dim ds As New DataSet
    Dim da As OleDb.OleDbDataAdapter
    Dim sql As String

con.ConnectionString = "
                 PROVIDER=Microsoft.Jet.OLEDB.4.0;
                 Data Source = D:\.Net Programs\DB Experiments\AddressBook.mdb"

        con.Open()
        sql = "SELECT * FROM tblContacts where Name=? and City=?"
        da = New OleDb.OleDbDataAdapter(sql, con)
        da.Fill(ds, "AddressBook")
        con.Close()

3 个答案:

答案 0 :(得分:3)

我首先创建一个OleDbCommand对象并使用此对象创建OleDbDataAdapter

Imports Data.OleDb

dim cmd as new OleDbCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * FROM tblContacts where Name=? and City=?"

' Here we add the parameters in the same order they appear in the
' CommandText. The Name of the paramters can be anything when using
' a Jet database, only the order is important.
cmd.Parameters.Add("@Name", OleDbType.VarChar).value = "SLaks"
cmd.Parameters.Add("@City", OleDbType.VarChar).value = "New-York"

Dim da as new OleDbDataAdapter(cmd)

' Here you can use the Data Adapter as you would normally do.

我希望这会有所帮助。

答案 1 :(得分:0)

呼叫

da.SelectCommand.Parameters.AddWithValue("paramName", someValue);

答案 2 :(得分:0)

为什么不直接构建最终的Sql?

sql = "SELECT * FROM tblContacts where Name='" & myName & "' and City='" & myCity & "'"

性能或安全性是否会有所不同或......?