我正在尝试创建一个图书馆管理系统,我是编码的初学者。我遇到的问题是我想在Visual Basic中按标题搜索我的书籍数据库,使用文本框和搜索按钮,并希望它以单独的形式显示结果。我将如何在visual basic中搜索我的数据库。
我已将数据库导入Visual Basic。我使用下面的查询使其在Microsoft Access中工作,但不能在Visual Basic中。 我在Microsoft访问中使用的查询是这样的:
SELECT Books.[Book ID], Books.Title, Books.Author, Books.Category, Books.Location, Books.[Fiction/Non-Fiction], Books.Loaned
FROM Books
WHERE (((Books.Title) Like [Search Certin Title] & "*"));
请帮助我。
答案 0 :(得分:1)
您需要使用ODBC,ADO或DAO连接来连接数据库。您需要使用特定的connection string,具体取决于您决定采用的选项。
ADO(ActiveX数据对象)使用OLEDB,因此您应该使用其中一个Jet或ACE连接字符串。下面是在VBA中使用ADO连接到Access数据库的示例。
Option Explicit
Sub queryADO()
Private Const pw = "password"
Dim rsData As ADODB.Recordset, rsConn As ADODB.Connection
Dim strSQL As String, strConn As String
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets("mySheet")
strConn = "C:\Users\lturner\Documents\myDatabase.accdb"
Set rsConn = New ADODB.Connection
With rsConn
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
strConn & ";Jet OLEDB:Database Password=" & pwd
.Open
End With
strSQL = "SELECT * FROM myTable"
Set rsData = rsConn.Execute(strSQL)
ws.Range("A1").CopyFromRecordset rsData
Set rsData = Nothing
Set rsConn = Nothing
End Sub
以上将查询结果复制到单元格A1中。您应该能够轻松地调整上述内容,以使用查询结果填充用户表单。如果您需要任何帮助,请与我们联系。
您可以在ADO,DAO和ODBC连接here之间找到对比。
答案 1 :(得分:1)
我找到了别人的代码并修改了它以使用我的应用程序 http://www.sattsoft.com/sourcecodes/details/1/4/vb-net-add-edit-delete-and-search-data-from-access-database.html
使用的代码如下:
Private Sub search_btn_Click(sender As Object, e As EventArgs) Handles search_btn.Click
Searched_Books_frm.Show()
Search_Record()
End Sub
Private Sub Search_Record()
'The Code Below is not Mine, But I modified it to work with my code. This Code below belongs to Christopher Tubig, Code from: http://goo.gl/113Jd7 (Url have been shortend for convenience) User Profile:
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT Books.[Book ID], Books.Title, Books.Author, Books.Category, Books.Location, Books.[Fiction/Non-Fiction], Books.Loaned FROM Books"
sSQL = sSQL & " Where Books.Title like '%" & Me.search_txt.Text & "%'"
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Searched_Books_frm.search_datagrid.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
这对我来说非常好:)