zoukankan      html  css  js  c++  java
  • Python 连接、操作数据库

    使用python3+pymysql

    一、安装python3

    a)         从网上下载安装吧

    二、安装pymysql

    https://pypi.python.org/pypi/PyMySQL

    https://github.com/PyMySQL/PyMySQL

    当然,最简单的安装方式还是使用pip命令。

    > pip install  PyMySQL

    安装完成后,查看pymysql是否安装成功:pip show pymysql

     

    二,创建MySQL

    执行下面的SQL语句,创建一张users 表。

     

     

    CREATE TABLE `users` (

        `id` INT(11) NOT NULL AUTO_INCREMENT,

        `email` VARCHAR(255) COLLATE utf8_bin NOT NULL,

        `password` VARCHAR(255) COLLATE utf8_bin NOT NULL,

        PRIMARY KEY (`id`)

    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin

    AUTO_INCREMENT=1 ;

    三,Python操作MySQL

    接下来才是重点,Python操作MySQL数据库。

    4.1插入数据:

     不管你使用的是什么工具或库,连接数据库这一步必不可少。host为数据库的主机IP地址,port为MySQL的默认端口号,user为数据的用户名,password为数据库的登录密码,db为数据库的名称。

      cursor()方法创建数据库游标。

      execute()方法执行SQL语句。

      commit()将数据库的操作真正的提交到数据。

    代码如下:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Author: Dang Kai
    # @Date: 2018-07-27 10:35:57
    # @Last Modified time: 2018-07-27 14:32:08
    # @E-mail: 1370465454@qq.com
    # @Description:
    
    
    import pymysql.cursors
    
    # 连接数据库
    
    
    def connect_mysql(host, port, user, password, db):
    
        connection = pymysql.connect(host=host, port=port, user=user, password=password,
                                     db=db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
        print('connect success')
    
    config = {
            'host': 'localhost',
            'port': 3306,
            'user': 'root',
            'password': 'dk137046',
            'db': 'test',
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor,
        }
    '''使用字典连接'''
    connection = pymysql.connect(**config)
    print('connect success')
    
    
    def insert_Mysql(config, sql):
        '''插入sql'''
        cursor = connection.cursor()
        cursor.execute(sql)
        connection.commit()
        print('插入成功')
        # result=cursor.fetchone()
        # print(result)
        connection.close()
    
    
    if __name__ == '__main__':
        # connect_mysql('localhost', 3306, 'root', 'dk137046', 'test')
        
        insert_sql = "INSERT INTO users (email,password) VALUES ('1370465454@qq.com','123456');"
        insert_Mysql(config, insert_sql)

    4.2. 查询数据

    接下来的操作就是数据库的查询了。

      fetchone() 用于查询单条数据。

      fetchall() 用于查询多条数据。

      close() 最后不要忘记了关闭数据连接。

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Author: Dang Kai
    # @Date: 2018-07-27 10:35:57
    # @Last Modified time: 2018-07-27 14:33:47
    # @E-mail: 1370465454@qq.com
    # @Description:
    
    
    import pymysql.cursors
    
    # 连接数据库
    
    
    def connect_mysql(host, port, user, password, db):
    
        connection = pymysql.connect(host=host, port=port, user=user, password=password,
                                     db=db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
        print('connect success')
    
    config = {
            'host': 'localhost',
            'port': 3306,
            'user': 'root',
            'password': 'dk137046',
            'db': 'test',
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor,
        }
    '''使用字典连接'''
    connection = pymysql.connect(**config)
    print('connect success')
    
    
    def insert_Mysql(config, sql):
        '''插入sql'''
        cursor = connection.cursor()
        cursor.execute(sql)
        # connection.commit()
        # print('插入数据成功')
        result=cursor.fetchone()
        print(result)
        result1=cursor.fetchall()
        # print(result1)
        for data in result1:
            print(data)
        connection.close()
    
    
    if __name__ == '__main__':
        # connect_mysql('localhost', 3306, 'root', 'dk137046', 'test')
        
        # insert_sql = "INSERT INTO users (email,password) VALUES ('1370465454@qq.com','123456');"
        # insert_Mysql(config, insert_sql)
        query_sel="SELECT * FROM users"
        insert_Mysql(config, query_sel)
        

      运行结果:

    connect success
    {'id': 1, 'email': '1370465454@qq.com', 'password': '123456'}
    {'id': 2, 'email': '1370465454@qq.com', 'password': '123456'}
    {'id': 3, 'email': '1370465454@qq.com', 'password': '123456'}
    {'id': 26, 'email': '1370465454@qq.com', 'password': '123456'}
    {'id': 29, 'email': '1370465454@qq.com', 'password': '123456'}
    {'id': 30, 'email': '1370465454@qq.com', 'password': '123456'}
    {'id': 31, 'email': '1370465454@qq.com', 'password': '123456'}
    [Finished in 0.2s]

    目前还在学习中,希望会对大家有所帮助,觉得不错,就点赞支持一下。 另外,转载时请附带链接。谢谢!
  • 相关阅读:
    ffmpeg 编译IOS静态库
    冲刺总结——第一篇
    openssl基础知识以及部分命令详解
    电子公文传输系统
    第五组课程设计—小组总结
    学习经验总结
    QtCreator:没CDB二进制档可用为二进制格式在'x86windowsmsvc2008pe32bit'"
    printf格式化输出
    DELL T110 安装windows server 2003
    visualSVN+花生壳实现外网访问局域网内SVN
  • 原文地址:https://www.cnblogs.com/dangkai/p/9377436.html
Copyright © 2011-2022 走看看