VB.NET connects to oracle through OleDbConnection to query data example

I. Introduction

1. Purpose

This article realizes that VB.Net connects to oracle to query data through OleDbConnection, and displays the data to TextBox1.

2. Database version

select * from v$version; 

    BANNER
1 Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
2 PL/SQL Release 11.2.0.1.0 - Production
3 CORE 11.2.0.1.0 Production
4 TNS for 64-bit Windows: Version 11.2.0.1.0 - Production
5 NLSRTL Version 11.2.0.1.0 - Production

3.IDE version

Microsoft Visual C++ 2019

Second, the source code

1. Page design

2. Click on the event to query the database

Imports System.Data.OleDb

Public Class oracleDemo

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        '创建数据库连接
        Dim oleDbCon As New OleDbConnection
        '连接字符串192.168.31.55
        Dim conStr = "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))
(CONNECT_DATA=(SERVICE_NAME=orcl)))"
        oleDbCon.ConnectionString = "Provider=OraOLEDB.Oracle;Data Source=" + conStr +
         ";user id=scott;password=root"
        'Command 对象提供执行 SQL命令的功能
        Dim oleDbCmd As New OleDbCommand()
        '打开连接
        oleDbCon.Open()
        '设置 Command 对象的连接属性
        oleDbCmd.Connection = oleDbCon
        '定义sql
        Dim sql = "select 'aa' from dual"
        '查询真正的数据库
        sql = "SELECT * FROM EMP --where empno = '7369'"
        oleDbCmd.CommandType = CommandType.Text
        '设置查询语句
        oleDbCmd.CommandText = sql
        'DataReader 对象提供只读方式的数据对象
        Dim dataRd As OleDbDataReader
        '查询数据
        dataRd = oleDbCmd.ExecuteReader()
        Dim a = "返回结果:"

        '这样只能查询出第一条结果 
        'If dataRd.Read() Then
        '    a += CStr(dataRd.GetValue(0))
        'Else
        '    MsgBox("错误")
        'End If

        '这样能查询出全部数据
        While dataRd.Read = True
            a += CStr(dataRd.GetValue(0))
            'TextBox1.Text.Append(str)
            a += ","
        End While

        '在TextBox1中显示显示查询结果
        TextBox1.Text = a
        dataRd.Close()
        oleDbCon.Close()
    End Sub

End Class
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw ==

Three, test

Four, matters needing attention

1. Exception: "OraOLEDB.Oracle" provider is not registered on the local computer

Prompt that this exception is handled as follows

Click: Project->Properties->Compile, uncheck "Prefer 32-bit (P)"

Guess you like

Origin blog.csdn.net/cs373616511/article/details/114498857