zoukankan      html  css  js  c++  java
  • Python 使用MySQL

    在导入MySQLdb之前,需要安装MySQLdb模块。使用pip安装,命令如下: pip install MySQL-python

    安装成功后,导入MySQLdb模块

    import MySQLdb

    连接数据库

    con = MySQLdb.connect(host='127.0.0.1', user = 'root', passwd = '', db = 'go')

    上面通过connect方法返回的con对象,即是数据库连接对象,它提供了以下方法
    cursor()方法用来创建一个游标对象:
    cur = con.cursor()

    游标对象有以下方法支持数据库的操作 
    execute()用来执行SQL语句
    executemany()用来执行多条sql语句
    close()用来关闭游标
    fetchone()用来从结果中取一条记录,并将游标指向下一条记录
    fetchmany()用来从结果中取多条记录
    fetchall()用来从结果中取出所有记录
    scroll()用于游标滚动

    #coding:utf-8
    import MySQLdb

    if __name__ == '__main__':

    con = MySQLdb.connect(host='127.0.0.1', user = 'root', passwd = '', db = 'go')

    cur = con.cursor()

    cur.execute('select * from user')

    #取出所有的数据
    all = cur.fetchall()
    print all

    #取出一条数据
    cur.execute('select * from user')
    one = cur.fetchone()
    print one

    #取出多条结果
    cur.execute('select * from user')
    many = cur.fetchmany()

    print many
    #执行插入一条语句
    cur.execute('insert into user(user_name,name)values("adssd","dksdksk")')
    #插入多条数据
    cur.executemany('insert into user(user_name,name)values(%s,%s)', [('22222', '3333'), ('33333', '4444')])
    #必须执行commit()
    con.commit()
    con.close()



  • 相关阅读:
    redis的数据持久化再讲 关于redisAOF RDB工作原理
    关于redis的持久化数据 RDB,AOF
    关于redis
    docker-compose的使用
    dockerfile定制镜像的使用
    docker常用命令
    关于这两天
    eclipse tomcat找不到或无法加载
    关于jdk代理和cglib代理
    scp 跨机远程拷贝
  • 原文地址:https://www.cnblogs.com/paulversion/p/8391375.html
Copyright © 2011-2022 走看看