当前位置: 代码网 > it编程>编程语言>C# > C#/C++ 通过ODBC连接OceanBase Oracle租户的详细过程

C#/C++ 通过ODBC连接OceanBase Oracle租户的详细过程

2024年05月26日 C# 我要评论
概述近期我们项目正处于将oracle数据库迁移到oceanbase oracle租户模式的阶段。考虑到我们项目采用了c++和c#混合开发,并且使用了多种技术,因此存在多种数据库连接方式。然而,针对c#

概述

近期我们项目正处于将oracle数据库迁移到oceanbase oracle租户模式的阶段。考虑到我们项目采用了c++和c#混合开发,并且使用了多种技术,因此存在多种数据库连接方式。然而,针对c#连接oceanbase的案例相对较少,因此我特意记录下这一过程。

开放数据库互连(odbc)是微软公司开放服务结构(wosa,windows open services architecture)中有关数据库的一个组成部分,基本思想是为用户提供简单、标准、透明的数据库连接的公共编程接口,开发厂商根据 odbc 的标准去实现底层的驱动程序,这个驱动对用户是透明的,并允许根据不同的 dbms 采用不同的技术加以优化实现。

驱动下载

下载地址:https://www.oceanbase.com/softwarecenter-cloud

根据平台类型选择驱动。

驱动配置

打开 odbc 数据源管理员:在 windows 中,按下 windows键 + r 打开“运行”对话框,然后输入 odbcad32 并按下 enter 键,这将打开 odbc 数据源管理员。

 选择系统的或用户的数据源:在 odbc 数据源管理员中,有两个选项卡:用户 dsn 和 系统 dsn。选择一个适合你的选项,通常建议选择 系统 dsn,因为它对所有用户都可用。

添加一个新的数据源:点击 添加 按钮,然后在弹出的对话框中选择 oceanbase odbc 2.0 driver 数据库。

配置数据源连接信息:在配置 oceanbase 数据库数据源时,你需要提供以下信息:

数据源名称(dsn):为你的数据源指定一个唯一的名称。这里命名为oceanbase odbc

描述:提供有关此数据源的描述,以便识别它。

 tns 服务名称:输入你要连接的 oracle 服务的 tns 服务名称。ip: xx.xx.xx.xx

用户名和密码:提供用于连接到 oracle 数据库的用户名和密码。

 username: 用户名@租户名#集群

测试连接:在完成配置后,你可以点击 测试连接 按钮来验证是否能够成功连接到 oceanbase oracle 数据库。

注意:不通过dsn也可以连接

c++ 代码案例

#include <stdio.h>
#include <assert.h>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <iostream>
void print_error(sqlsmallint handletype, sqlhandle handle) {
    sqlwchar sqlstate[6];
    sqlinteger nativeerror;
    sqlwchar sqlmessage[sql_max_message_length] = { 0 };
    sqlsmallint textlengthptr;
    sqlgetdiagrec(handletype, handle, 1, sqlstate, &nativeerror, sqlmessage, sql_max_message_length, &textlengthptr);
    std::wcerr << l"[" << sqlstate << l"] (" << nativeerror << l") " << sqlmessage << std::endl;
}
int main() {
    // allocate environment handle
    sqlhandle henv;
    sqlallochandle(sql_handle_env, sql_null_handle, &henv);
    sqlsetenvattr(henv, sql_attr_odbc_version, (sqlpointer)sql_ov_odbc3, 0);
    // allocate connection handle
    sqlhandle hdbc;
    sqlallochandle(sql_handle_dbc, henv, &hdbc);
    // connection string
    //使用dsn
    sqlwchar* connectionstring = (sqlwchar*)l"dsn=oceanbase odbc;uid=用户名@住户名#集群;pwd=密码";
    //不使用dsn
    //sqlwchar* connectionstring = (sqlwchar*)l"driver={oceanbase odbc 2.0 driver};server=xx.xx.xx.xx;port=2883;database=用户名;user=用户名@住户名#集群;password=密码;option=3;";
    // connect to the database
    sqlreturn retcode = sqldriverconnect(hdbc, null, connectionstring, sql_nts, null, 0, null, sql_driver_noprompt);
    if (retcode != sql_success && retcode != sql_success_with_info) {
        std::cerr << "error connecting to database:" << std::endl;
        print_error(sql_handle_dbc, hdbc);
        return 1;
    }
    std::cout << "connected to database successfully!" << std::endl;
    // allocate statement handle
    sqlhandle hstmt;
    sqlallochandle(sql_handle_stmt, hdbc, &hstmt);
    // execute a query
    sqlwchar* query = (sqlwchar*)l"select * from tiers where rownum <= 1;";
    retcode = sqlexecdirect(hstmt, query, sql_nts);
    if (retcode != sql_success && retcode != sql_success_with_info) {
        std::cerr << "error executing query:" << std::endl;
        print_error(sql_handle_stmt, hstmt);
        sqlfreehandle(sql_handle_stmt, hstmt);
        sqldisconnect(hdbc);
        sqlfreehandle(sql_handle_dbc, hdbc);
        sqlfreehandle(sql_handle_env, henv);
        return 1;
    }
    // fetch and print results
    sqlchar name[256];
    sqllen namelen;
    while (sqlfetch(hstmt) == sql_success) {
        sqlgetdata(hstmt, 1, sql_c_char, name, sizeof(name), &namelen);
        std::cout << "name: " << name << std::endl;
    }
    // cleanup
    sqlfreehandle(sql_handle_stmt, hstmt);
    sqldisconnect(hdbc);
    sqlfreehandle(sql_handle_dbc, hdbc);
    sqlfreehandle(sql_handle_env, henv);
    return 0;
}

c# 代码案例

using system;
using system.data.odbc;
namespace consoleapp
{
    internal class program
    {
        static void main(string[] args)
        {
            //使用dsn
            string connectionstring = "dsn=oceanbase odbc;uid=用户名@住户名#集群;pwd=你的密码;";
            //不使用dsn
            //string connectionstring = "driver={oceanbase odbc 2.0 driver};server=xx.xx.xx.xx;port=2883;database=用户名;user=用户名@住户名#集群;;password=密码;option=3;";
            using (odbcconnection connection = new odbcconnection(connectionstring))
            {
                try
                {
                    connection.open();
                    console.writeline("connected to oracle database!");
                    // perform database operations here
                    string query = "select *from tiers where rownum <= 1;";
                    using (odbccommand command = new odbccommand(query, connection))
                    {
                        using (odbcdatareader reader = command.executereader())
                        {
                            while (reader.read())
                            {
                                int id = reader.getint32(0); // 假设第一列是 id
                                string name = reader.getstring(1); // 假设第二列是 name
                                console.writeline($"id: {id}, name: {name}");
                            }
                        }
                    }
                    connection.close();
                }
        }
    }
}

nhibernate示例

安装nhibernate

使用nuget包管理器安装nhibernate。你可以在visual studio中打开nuget包管理器控制台,然后运行以下命令:

install-package nhibernate

这将自动下载并安装nhibernate及其所有依赖项到你的项目中。

配置nhibernate

nhibernate.cfg.xml
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
        <property name="connection.driver_class">nhibernate.driver.odbcdriver</property>
        <!--<property name="connection.connection_string">dsn=oceanbase odbc;database=用户名;uid=用户名@住户名#集群;pwd=密码;</property>-->
        <property name="connection.connection_string">driver={oceanbase odbc 2.0 driver};server=xx.xx.xx.xx;port=2883;database=用户名;uid=用户名@住户名#集群;pwd=密码;</property>
        <property name="dialect">nhibernate.dialect.oracle10gdialect</property>
    </session-factory>
</hibernate-configuration>

配置映射类

public class testentity
{
    public virtual int ident { get; set; }
    public virtual string name { get; set; }
}
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="consoleapp2.testentity, consoleapp2" table="testentity">
        <id name="ident" column="ident" />
        <property name="name" column="name" />
        <!-- 其他属性映射... -->
    </class>
</hibernate-mapping>

查询案例

using nhibernate.cfg;
using system;
using system.io;
class program
{
    static void main(string[] args)
    {
        string basedirectory = appdomain.currentdomain.basedirectory;
        var cfg = new configuration().configure(path.combine(basedirectory, "nhibernate.cfg.xml"));
        cfg.addfile(path.combine(basedirectory, "testentity.xml"));
        var sessionfactory = cfg.buildsessionfactory();
        using (var session = sessionfactory.opensession())
        {
            var query = session.createquery("from testentity")
                .setmaxresults(10);
            var results = query.list();
        }
    }
}

到此这篇关于c#/c++ 通过odbc连接oceanbase oracle租户的文章就介绍到这了,更多相关c++ 连接oceanbase oracle租户内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com