暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Python 应用程序连接 OceanBase 数据库

本文介绍如何通过 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()
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论