Python入门(6)连接MySQL

依赖pymysql

如果没有安装pymysql,需要执行安装命令

pip3 install pymysql

完整代码

# coding: utf-8
import json

#mysql
import pymysql.cursors

def readJson(f):
    return json.load(open(f,'r',encoding='utf-8'))

if __name__ == "__main__":
    

    # Connect to the database
    print('连接数据库')
    connection = pymysql.connect(host='localhost',port=3306,user='root',
password='root',db='jzap',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
    
    print('读取json文件')

    try:

        with connection.cursor() as cursor:
        '''with connection.cursor() as cursor:
            # Create a new record
            sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
            cursor.execute(sql, ('[email protected]', 'very-secret'))
            # connection is not autocommit by default. So you must commit to save
            # your changes.
            connection.commit()
        '''

        '''
        with connection.cursor() as cursor:
            # Read a single record
            sql = "SELECT `id`, `cn_name` FROM `sys_user` WHERE `id`=%s"

            cursor.execute(sql, ('00000001000135acef638a',))

            result = cursor.fetchone()

            print(result)
        '''
    finally:
        connection.close()

    '''
    
    

    '''

你可能感兴趣的:(Python入门(6)连接MySQL)