• python中的mysql数据库


    插入,更新,删除执行conn.execute()后需要进行conn.commit()操作

    cursor.fetchone():将只取最上面的第一条结果,返回单个元组如('id','title'),然后多次使用cursor.fetchone(),依次取得下一条结果,直到为空。

    cursor.fetchall() :将返回所有结果,返回二维元组,如(('id','title'),('id','title')),

    如果select本身取的时候只有一条数据时:

    cursor.fetchone():将只返回一条结果,返回单个元组如('id','title')。

    cursor.fetchall() :也将返回所有结果,返回二维元组,如(('id','title'),),

    user_id = "test123"
    password = "password"

    con.execute('insert into Login values("%s", "%s")' %
                 (user_id, password))

    数据库查询操作:

    fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
    fetchall():接收全部的返回结果行.
    rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

    查询EMPLOYEE表中salary(工资)字段大于1000的所有数据:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-

    import MySQLdb

    # 打开数据库连接
    db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    # SQL 查询语句
    sql = "SELECT * FROM EMPLOYEE
           WHERE INCOME > '%d'" % (1000)
    try:
       # 执行SQL语句
       cursor.execute(sql)
       # 获取所有记录列表
       results = cursor.fetchall()
       for row in results:
          fname = row[0]
          lname = row[1]
          age = row[2]
          sex = row[3]
          income = row[4]
          # 打印结果
          print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" %
                 (fname, lname, age, sex, income )
    except:
       print "Error: unable to fecth data"

    # 关闭数据库连接
    db.close()

  • 相关阅读:
    Springboot配置文件解析器
    ThreadLocal的简单使用和实现原理
    hashCode()方法对HashMap的性能影响
    Thread中的join()方法
    Windows使用MongoDB,以及索引创建
    Android--我的Butterknife黄油刀怎么找不到控件了!!!
    Android--RecyclerView的封装使用
    Android--自定义加载框
    Android--Retrofit+RxJava的简单封装(三)
    Android--Retrofit+RxJava(二)
  • 原文地址:https://www.cnblogs.com/linqiuhua/p/7717604.html
Copyright © 2020-2023  润新知