起因是,mysql无法连接远程的机器,但是用python却可以。

写了这个脚本

import pymysql
import argparse

# MySQL 连接信息
host = '192.168.1.1'  # 替换为你的 MySQL 服务器 IP
user = 'ecology'         # 替换为你的 MySQL 用户名
password = 'ecology1234'  # 替换为你的 MySQL 用户密码
database = 'ecology'   # 替换为数据库名




def execute_query(query):
    try:
        # 建立连接
        connection = pymysql.connect(
            host=host,
            user=user,
            password=password,
            database=database,
            port=3306,   # MySQL 默认端口
            connect_timeout=5  # 设置超时时间
        )
        print("Connection successful!")

        # 执行查询
        with connection.cursor() as cursor:
            cursor.execute(query)
            results = cursor.fetchall()  # 获取所有结果
            columns = [desc[0] for desc in cursor.description] if cursor.description else []  # 获取列名

            print("Query executed successfully.")
            return columns, results  # 返回列名和查询结果

    except pymysql.MySQLError as e:
        print("Connection failed.")
        print(f"Error: {e}")
        return None, None

    finally:
        # 关闭连接
        if 'connection' in locals() and connection.open:
            connection.close()
            print("Connection closed.")

if __name__ == "__main__":
    # 设置命令行参数解析
    parser = argparse.ArgumentParser(description="Execute a MySQL query from command line.")
    parser.add_argument("query", type=str, help="The SQL query to execute.")
    args = parser.parse_args()

    # 从命令行参数接收 SQL 查询
    query = args.query
    columns, results = execute_query(query)

    # 打印查询结果
    if results is not None:
        # 打印列名
        print("Columns:", columns)
        # 打印每一行结果
        for row in results:
            print(row)

用法:
python testmy.py "SHOW COLUMNS FROM ws_datasource;"
python testmy.py "select * FROM weaver_sso LIMIT 100;"

标签: none

添加新评论

  • 上一篇: msrdp
  • 下一篇: 没有了