在之前我们通过《三篇文章帮你搞定怎样进行mysql数据库学习之mysql库创建表》对mysql数据库学习进行了深一层级的学习,现在我们就来进行mysql数据库学习最关键的知识点——mysql跨库查询。
在学习mysql跨库查询前,我们要先学会数据库插入操作:
以下实例使用执行 sql insert 语句向表 employee 插入记录:
#!/usr/bin/python# -*- coding: utf-8 -*-import mysqldb# 打开数据库连接db = mysqldb.connect("localhost", "testuser", "test123", "testdb", charset='utf8' )# 使用cursor()方法获取操作游标 cursor = db.cursor()# sql 插入语句sql = """insert into employee(first_name, last_name, age, sex, income) values ('mac', 'mohan', 20, 'm', 2000)"""try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit()except: # rollback in case there is any error db.rollback()# 关闭数据库连接db.close()
数据库查询操作
python查询mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
1.fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
2.fetchall():接收全部的返回结果行.
3.rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
实例:
查询employee表中salary(工资)字段大于1000的所有数据:
#!/usr/bin/python# -*- coding: utf-8 -*-import mysqldb# 打开数据库连接db = mysqldb.connect("localhost", "testuser", "test123", "testdb", charset='utf8' )# 使用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()
以上就是三篇文章帮你搞定怎样进行mysql数据库学习之mysql跨库查询的详细内容。