python访问SQL数据库

时间:2024-10-02 19:43:55

Step 1  创建一个数据库

Step  2   安装mysql-connector-python

pip install mysql-connector-python

Step  3 访问mysql,并查询表

import mysql.connector


def connect_and_query():
    try:
        # 连接到MySQL数据库
        connection = mysql.connector.connect(
            host='localhost',  # 数据库主机地址
            user='yourusername',  # 数据库用户名
            password='yourpassword',  # 数据库密码
            database='yourdatabase'  # 数据库名
        )

        if connection.is_connected():
            db_Info = connection.get_server_info()
            print("成功连接到MySQL数据库,MySQL 服务器版本为 ", db_Info)

            cursor = connection.cursor()
            cursor.execute("select database();")
            record = cursor.fetchone()
            print("你已连接到数据库: ", record)

            # 执行一个简单的查询
            cursor.execute("SELECT * FROM your_table_name LIMIT 5;")  # 替换your_table_name为你的表名
            rows = cursor.fetchall()
            for row in rows:
                print(row)

    except mysql.connector.Error as e:
        print("连接或查询出错,错误为 ", e)

    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL连接已关闭")


if __name__ == "__main__":
    connect_and_query()

127.0.0.1是本地地址