pip install pymysql
import pymysql db = pymysql.connect(host="数据库地址", user="用户名", password="密码", port=3306,#int not str database="数据库名", charset='utf8')
cursor = db.cursor()
# 如果数据表已经存在使用execute()方法删除表。 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # 创建数据表SQL语句 sql = """CREATE TABLE EMPLOYEE ( id int(7) NOT NULL auto_increment, FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT,primary key(id))ENGINE=InnoDB DEFAULT CHARSET=utf8""" cursor.execute(sql)
# SQL 插入语句 sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" try: cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback()
# SQL 查询语句 sql = "SELECT * FROM EMPLOYEE WHERE INCOME > {}".format(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={},lname={},age={},sex={},income={}".format(fname, lname, age, sex, income)) except: print("Error: unable to fecth data")
fetchone(): 获取单条数据,返回结果行元组,若无结果,返回null;
rowcount:获取下一个查询结果集,是一个对象;
fetchall():获取多条数据元组;若无结果,返回()。
备注:在MySQL中是NULL,而在Python中则是None。
# SQL 更新语句 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '{}'".format('M') try: cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback()
# SQL 刪除语句 sql = "DELETE FROM EMPLOYEE WHERE AGE > {}".format(20) try: cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback()
cursor.close() db.close()