zoukankan      html  css  js  c++  java
  • 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), '女'),)
    

      

  • 相关阅读:
    方差分析
    Rust 指定安装目录
    perl 子函数传入多个数组
    perl 获取目录信息
    R绘图布局包 customLayout
    C语言 自定义函数按行读入文件2
    C语言 自定义函数按行读入文件
    C语言按行读入文件
    sed删除指定行
    mybatis 批量更新
  • 原文地址:https://www.cnblogs.com/yaoze2018/p/12423398.html
Copyright © 2011-2022 走看看