Python 连接、操作数据库

使用python3+pymysql

一、安装python3

a)         从网上下载安装吧

二、安装pymysql

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

https://github.com/PyMySQL/PyMySQL

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

> pip install  PyMySQL

扫描二维码关注公众号,回复: 2409963 查看本文章

安装完成后,查看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 ('[email protected]','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 ('[email protected]','123456');"
    # insert_Mysql(config, insert_sql)
    query_sel="SELECT * FROM users"
    insert_Mysql(config, query_sel)
    

  运行结果:

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

猜你喜欢

转载自www.cnblogs.com/dangkai/p/9377436.html