#!/usr/bin/env python # -*- coding: utf-8 -*- """ 数据库创建脚本 用于在 PostgreSQL 服务器上创建 ai_vision 数据库 """ import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT # 数据库连接信息 DB_HOST = "331002.xyz" DB_PORT = 2022 DB_USER = "user_xREpkJ" DB_PASSWORD = "password_DZz8DQ" DB_NAME = "ai_vision" def create_database(): """创建数据库""" try: # 连接到默认的 postgres 数据库 print(f"🔗 正在连接到 PostgreSQL 服务器 {DB_HOST}:{DB_PORT}...") conn = psycopg2.connect( host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PASSWORD, database="postgres" # 先连接到默认数据库 ) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() # 检查数据库是否存在 cursor.execute(f"SELECT 1 FROM pg_database WHERE datname = '{DB_NAME}'") exists = cursor.fetchone() if exists: print(f"✅ 数据库 {DB_NAME} 已经存在") else: # 创建数据库 print(f"🔧 正在创建数据库 {DB_NAME}...") cursor.execute(f'CREATE DATABASE {DB_NAME}') print(f"✅ 数据库 {DB_NAME} 创建成功!") cursor.close() conn.close() print(f"\n📊 数据库信息:") print(f" 主机: {DB_HOST}:{DB_PORT}") print(f" 数据库名: {DB_NAME}") print(f" 用户: {DB_USER}") print(f"\n💡 下一步:运行 python init_db.py 创建数据表") except psycopg2.Error as e: print(f"❌ 数据库操作失败: {e}") print(f"\n可能的原因:") print(f" 1. 用户 {DB_USER} 没有创建数据库的权限") print(f" 2. 网络连接问题") print(f" 3. 数据库服务器配置限制") except Exception as e: print(f"❌ 发生错误: {e}") if __name__ == '__main__': create_database()