ITPub博客

首页 > 数据库 > 国内数据库 > 【手摸手玩转 OceanBase 11】Python 应用程序连接 OceanBase 数据库

【手摸手玩转 OceanBase 11】Python 应用程序连接 OceanBase 数据库

原创 国内数据库 作者:13579NB232 时间:2023-01-18 17:47:53 0 删除 编辑

本文介绍如何通过 Python 驱动连接 OceanBase 数据库。

Python3.x 系列(使用 PyMySQL)

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

有关 PyMySQL 的详细信息,您可参考  官方文档 和  相关 API 参考文档。

PyMySQL 安装

在使用 PyMySQL 之前需要确保 PyMySQL 已安装。您可前往  下载 界面进行下载安装。

PyMySQL 有以下两种安装方式:

  1. 使用命令行安装

    python3 -m pip install PyMySQL
  2. 源码编译

    git clone https://github.com/PyMySQL/PyMySQL
    cd PyMySQL/
    python3 setup.py install

PyMySQL 使用

您可通过以下命令设置 connect 对象。

conn = pymysql.connect(
    host="localhost", 
    port=2881,user="root", 
    passwd="", 
    db="testdb"
)

示例:

#!/usr/bin/python3
import pymysql
conn = pymysql.connect(host="localhost", port=2881,
                       user="root", passwd="", db="testdb")
try:
    with conn.cursor() as cur:
        cur.execute('SELECT * FROM cities')
        ans = cur.fetchall()
        print(ans)
finally:
    conn.close()

Python2.x 系列(使用 MySQL-python)

MySQL-python 是 Python2.X 版本中用于连接 MySQL 服务器的一个库。

安装 MySQL-python 是为了使用 MySQLdb 连接和操作 OceanBase 数据库。MySQLdb 是 Python 连接 MySQL 数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 建立。

有关 MySQL-python 的详细信息,您可参考  官方文档 和  Github 文档.

MySQL-python 安装

首先您需确保计算机上有 Python2.X 的环境,之后使用 pip 安装 MySQL-python。

pip install MySQL-python

MySQL-python 使用

您可通过以下命令设置 connect 对象。

conn= MySQLdb.connect(
    host='127.0.0.1',
    port = 2881,
    user='root',
    passwd='',
    db ='testdb'
)

示例:

#!/usr/bin/python2
import MySQLdb
conn= MySQLdb.connect(
    host='127.0.0.1',
    port = 2881,
    user='root',
    passwd='',
    db ='testdb'
)
try:
    cur = conn.cursor()
    cur.execute('SELECT * from cities')
    ans = cur.fetchall()
    print(ans)
    
finally:
    conn.close()


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70026124/viewspace-2932655/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2023-01-18

  • 博文量
    184
  • 访问量
    93224