环境准备
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2.X中则使用mysqldb。
安装的话直接使用pip安装即可。
pip install PyMySQL
数据库连接
import pymysql # 打开数据库连接 db = pymysql.connect("localhost","testuser","test123","TESTDB" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法获取单条数据 data = cursor.fetchone() print ("Database version : %s " % data) # 关闭数据库连接 db.close()
创建数据库表
# 使用 execute() 方法执行 SQL,如果表存在则删除 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # 使用预处理语句创建表 sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, DAY DATE, time DATETIME, COMMENT,TEXT, SEX CHAR(1), INCOME FLOAT )""" cursor.execute(sql)
数据库插入操作
# 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: # 如果发生错误则回滚 db.rollback()
数据库查询操作
Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
- fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
- fetchall(): 接收全部的返回结果行.
- rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
# SQL 查询语句 sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > %s" % (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=%s,sex=%s,income=%s" % \ (fname, lname, age, sex, income )) except: print ("Error: unable to fetch data")
数据库更新操作
更新操作用于更新数据表的的数据,以下实例将 TESTDB 表中 SEX 为 ‘M’ 的 AGE 字段递增 1:
# SQL 更新语句 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try: # 执行SQL语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback()
删除操作
删除操作用于删除数据表中的数据,以下实例演示了删除数据表 EMPLOYEE 中 AGE 大于 20并小于100 的所有数据。
# SQL 删除语句 sql = "DELETE FROM EMPLOYEE WHERE AGE > %s AND AGE < %s" % (20,100) try: # 执行SQL语句 cursor.execute(sql) # 提交修改 db.commit() except: # 发生错误时回滚 db.rollback()
本文转载自菜鸟教程。
最聪明的处世之术是,
既对世俗投以白眼,
又愿与其同流合污。
《侏儒警语》——芥川龙之介


评论
745969 114808Some genuinely good and utilitarian information on this internet website , likewise I believe the style and style contains superb capabilities. 227644
262742 827976Wow, suprisingly I never knew this. Maintain up with great posts. 731820
417242 830454Good day! Do you know if they make any plugins to protect against hackers? Im kinda paranoid about losing everything Ive worked hard on. Any suggestions? 148406
618277 39244Excellent editorial! Would like took pleasure the specific following. Im hoping to learn to read a whole lot much more of you. Theres no doubt that you possess tremendous awareness and even imagination. I happen to be very highly fascinated employing this critical data. 768862
73709 632256But a smiling visitor here to share the really like (:, btw wonderful pattern . 258377