以下是通过Python驱动psycopg2连接和使用Kingbase数据库的实战指南:
1. 环境准备
确保已安装以下组件:
- Python 3.6+
psycopg2库(需兼容Kingbase的PostgreSQL协议)- Kingbase数据库客户端驱动(如
kingbase-odbc或kingbase-psql)
安装psycopg2:
bash
pip install psycopg2-binary # 或 psycopg2
2. 连接Kingbase数据库
Kingbase兼容PostgreSQL协议,可直接使用psycopg2连接。示例代码:
python
import psycopg2
# 连接参数配置
conn_params = {
"dbname": "your_dbname", # 数据库名
"user": "your_username", # 用户名
"password": "your_password", # 密码
"host": "127.0.0.1", # 数据库IP
"port": "54321" # Kingbase默认端口(可能非5432)
}
try:
# 建立连接
conn = psycopg2.connect(**conn_params)
print("连接成功!")
# 创建游标
cursor = conn.cursor()
# 示例:查询数据库版本
cursor.execute("SELECT version();")
db_version = cursor.fetchone()
print(f"数据库版本: {db_version[0]}")
except psycopg2.Error as e:
print(f"连接失败: {e}")
finally:
# 关闭连接
if conn:
cursor.close()
conn.close()
3. 执行SQL操作
3.1 查询数据
python
cursor.execute("SELECT id, name FROM users WHERE age > %s;", (18,))
results = cursor.fetchall()
for row in results:
print(f"ID: {row[0]}, Name: {row[1]}")
3.2 插入数据
python
insert_sql = """
INSERT INTO users (id, name, age)
VALUES (%s, %s, %s);
"""
data = (101, "张三", 25)
cursor.execute(insert_sql, data)
conn.commit() # 提交事务
3.3 事务管理
python
try:
cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;")
cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE user_id = 2;")
conn.commit() # 提交事务
except Exception as e:
conn.rollback() # 回滚事务
print(f"事务失败: {e}")
4. 高级用法
4.1 参数化查询防注入
始终使用%s占位符避免SQL注入:
python
cursor.execute("SELECT * FROM products WHERE price > %s AND category = %s;", (50, "电子产品"))
4.2 使用上下文管理器
自动管理连接和游标生命周期:
python
with psycopg2.connect(**conn_params) as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM orders;")
count = cursor.fetchone()[0]
print(f"订单总数: {count}")
4.3 处理二进制数据(如BLOB)
python
# 插入二进制数据(如图片)
with open('image.png', 'rb') as f:
binary_data = f.read()
cursor.execute("INSERT INTO images (data) VALUES (%s);", (psycopg2.Binary(binary_data),))
5. 常见问题解决
5.1 连接超时
在连接参数中添加超时设置:
python
conn_params["connect_timeout"] = 10 # 10秒超时
5.2 SSL连接
若Kingbase启用SSL:
python
conn_params["sslmode"] = "require"
conn_params["sslrootcert"] = "/path/to/rootcert.pem"
6. 完整示例
python
import psycopg2
def kingbase_demo():
conn = None
try:
conn = psycopg2.connect(
dbname="test_db",
user="admin",
password="secure_pwd",
host="10.0.0.1",
port="54321"
)
cursor = conn.cursor()
# 创建表
cursor.execute("""
CREATE TABLE IF NOT EXISTS employees (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
salary NUMERIC(10, 2)
);
""")
# 插入数据
cursor.execute("INSERT INTO employees (name, salary) VALUES (%s, %s);", ("李四", 8500.50))
# 查询数据
cursor.execute("SELECT * FROM employees;")
for row in cursor.fetchall():
print(f"员工: {row[1]}, 薪资: {row[2]}")
conn.commit()
except psycopg2.Error as e:
print(f"错误: {e}")
if conn:
conn.rollback()
finally:
if conn:
cursor.close()
conn.close()
if __name__ == "__main__":
kingbase_demo()
通过以上步骤,您已掌握Python使用psycopg2操作Kingbase数据库的核心方法。实际部署时需根据网络环境、安全策略调整连接参数。