码迷,mamicode.com
首页 > 数据库 > 详细

python中的mysql数据库

时间:2017-10-23 18:15:10      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:查询   对象   更新   mysqldb   data   imp   连接   localhost   mysq   

插入,更新,删除执行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()

python中的mysql数据库

标签:查询   对象   更新   mysqldb   data   imp   连接   localhost   mysq   

原文地址:http://www.cnblogs.com/linqiuhua/p/7717604.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!