python如何连接mysql

2025-11-06 01:35:24

1、安装Python开发环境

安装MySQL数据库

安装Python连接MySQL的依赖包MySQLdb

2、编写代码文件python_connect_mysql.py

3、#! /usr/bin/env python

#coding: utf8

import MySQLdb

if __name__ == "__main__":

    conn = None

    try:

        config = {"host":'127.0.0.1',

                "port":3306,

                "user":'test',

                "passwd":'12345678',

                "db":'test',

                "charset":'utf8'}

        conn = MySQLdb.connect(**config)

        conn.autocommit(True)

        cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)

        cursor.execute("select name,age from tbtest")

        rows = cursor.fetchall()

        for row in rows:

            print row["name"]

            print row["age"]

    except Exception, e:

        print str(e)

    finally:

        if conn:

            conn.close()

4、执行代码:

python python_connect_mysql.py

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢