Python执行sql语句

1.在python环境ok的情况下,需要用到pymysql模块,首先需要安装pymysql模块

 

在命令行中执行pip install pymysql即可

 2.

 

 

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql
db = pymysql.connect(
    host = 'localhost',
    port = 3306,
    user = 'yaoze',
    password = '123456',
    charset = 'utf8',
    database = 'pymysql'
)

cur = db.cursor()
cur.execute('select * from student;')
print('ok')
data1 = cur.fetchone()#获取结果集第1行  注:结果集默认为元组,且获取一次后该条数据就会被从结果集中删除
data2 = cur.fetchmany(5)#获取结果集第5行
data3 = cur.fetchall()#获取结果集全部 
print(data1)
print(data2)
print(data3)
db.close()

结果如下,可见获取一次后该条数据就会被从结果集中删除

ok
('01', '赵雷', datetime.datetime(1990, 1, 1, 0, 0), '男')
(('02', '钱电', datetime.datetime(1990, 12, 21, 0, 0), '男'), ('03', '孙风', datetime.datetime(1990, 12, 20, 0, 0), '男'))
() 

3.

#! /usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
def connect_mysql(sql):
    db = pymysql.connect(
        host = 'localhost',
        port = 3306,
        user = 'yaoze',
        password = '123456',
        database = 'pymysql',
        charset = 'utf8'
    )
    cur = db.cursor()
    cur.execute(sql)
    data = cur.fetchall()
    print(data)
    db.close()
if __name__=='__main__':
    sql1 = 'select * from student where sid = 3;'
    sql2 = "select * from student where sname ='赵六';"
    connect_mysql(sql1)
    connect_mysql(sql2)

  

结果为:

(('03', '孙风', datetime.datetime(1990, 12, 20, 0, 0), '男'),)
(('12', '赵六', datetime.datetime(2013, 6, 13, 0, 0), '女'),)

  

 

posted @ 2020-03-05 22:42  Avicii_2018  阅读(3667)  评论(0编辑  收藏  举报