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

  • 相关阅读:
    Leetcode951. Flip Equivalent Binary Trees翻转等价二叉树
    Leetcode938. Range Sum of BST二叉搜索树的范围和
    Leetcode962. Maximum Width最大宽度坡 Ramp
    STL容器-deque-双端队列
    Leetcode950. Reveal Cards In Increasing Order按递增顺序显示卡牌
    idea修改运行内存
    Web服务器进程连接数和请求连接数
    Vue问题总结
    Vue项目搭建过程
    去掉vue 中的代码规范检测(Eslint验证)
  • 原文地址:https://www.cnblogs.com/linqiuhua/p/7717604.html
Copyright © 2011-2022 走看看