美文网首页
Python入门(6)连接MySQL

Python入门(6)连接MySQL

作者: 走码人 | 来源:发表于2022-11-29 14:47 被阅读0次

    依赖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, ('webmaster@python.org', '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

          本文链接:https://www.haomeiwen.com/subject/vfudfdtx.html