• 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), '女'),)
    

      

  • 相关阅读:
    linux下golang的配置
    为什么有闭包?
    分布式之高性能IO组件
    ECMAScript 5.1 Edition DOC 学习笔记
    直线光栅画法
    【计算机基础】三、指令与指令执行过程
    ThreadLocal的使用
    【设计模式】单例模式
    问题记录
    【Java基础】- 泛型
  • 原文地址:https://www.cnblogs.com/yaoze2018/p/12423398.html
Copyright © 2020-2023  润新知