zoukankan      html  css  js  c++  java
  • python mysql

    写操作:

    #安装PyMySQL:pip3 install PyMySQL
    #!/usr/bin/python3
    #coding=utf-8
     
    import pymysql
     
    # 打开数据库连接
    db = pymysql.connect("localhost","root","root","mypython" )
     
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()
     
    # SQL 插入语句
    sql = """insert into user set name='zzz',pwd='cccdd',insert_time='13241'"""
    try:
       # 执行sql语句
       cursor.execute(sql)
       # 提交到数据库执行
       db.commit()
       #获取自增id
       new_id = cursor.lastrowid  
    except:
       # 如果发生错误则回滚
       db.rollback()
     
    # 关闭数据库连接
    db.close()
    print(new_id)
    
    读操作单条:

    #!/usr/bin/python3
     
    import pymysql
     
    # 打开数据库连接
    db = pymysql.connect("localhost","root","root","mypython" )
     
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
     
    # 使用 execute()  方法执行 SQL 查询 
    cursor.execute("select * from user")
     
    # 使用 fetchone() 方法获取单条数据.
    data = cursor.fetchone()
     
    print (data)
     
    # 关闭数据库连接
    db.close()
    读操作多条:

    #!/usr/bin/python3
     
    import pymysql
     
    # 打开数据库连接
    db = pymysql.connect("localhost","root","root","mypython" )
     
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
     
    # SQL 查询语句
    sql = "SELECT * FROM user 
           WHERE id > '%d'" % (0)
    try:
       # 执行SQL语句
       cursor.execute(sql)
       # 获取所有记录列表
       results = cursor.fetchall()
       print (results)
    except:
       print ("Error: unable to fetch data")
     
    # 关闭数据库连接
    db.close()
    [{'id': 1, 'insert_time': 2147483647, 'pwd': 'ccc', 'name': 'zsc'}, {'id': 2, 'insert_time': 13241, 'pwd': 'cccdd', 'name': 'zzz'}]



  • 相关阅读:
    iOS:Core Data 中的简单ORM
    Win8:Snap 实现
    js: 删除node的所有child
    WinJS:Listview item 设置背景透明
    iOS: 消息通信中的Notification&KVO
    win8: 清除iframe的缓存
    What's New in iOS7,iOS7新特性介绍
    "Entity Framework数据插入性能追踪"读后总结
    夜,思考——我想要的到底是什么?
    【查询】—Entity Framework实例详解
  • 原文地址:https://www.cnblogs.com/fonyer/p/8871449.html
Copyright © 2011-2022 走看看