Before using Python2, MySQL connection using a MySQLdb. Now replaced python3.x, because MySQLdb module does not support Python3.x, so if you want to connect to the MySQL Python3.x PyMySQL need to install the module, the following describes the installation and common operations PyMySQL of.
First, install
pip install PyMySQL
Second, common operations
-
Query data
import pymysql # 连接数据库 conn = pymysql.connect( host='127.0.0.1', user='root', passwd='root', port=3306, db='test', charset='utf8' ) # 创建一个游标 cursor = conn.cursor() # 查询数据 sql = "select * from user" cursor.execute(sql) # 执行sql # 查询所有数据,返回结果默认以元组形式,所以可以进行迭代处理 for i in cursor.fetchall(): print(i) print('共查询到:', cursor.rowcount, '条数据。') # 获取第一行数据 result_1 = cursor.fetchone() print(result_1) # 获取前n行数据 result_3 = cursor.fetchmany(3) print(result_3) cursor.close() # 关闭游标 conn.close() # 关闭连接
-
Insert data
After executing the insert statement must be executed
.commit()
to commit the transaction, submitted after unification can insert multiple, otherwise操作无效
import pymysql # 连接数据库 conn = pymysql.connect( host='127.0.0.1', user='root', passwd='root', port=3306, db='test', charset='utf8' ) # 创建一个游标 cursor = conn.cursor() # 插入数据 # 数据直接写在sql后面 sql = "insert into username(id,name) values(%s, %s)" # 注意是%s,不是s% cursor.execute(sql, [3, '王五']) # 列表格式数据 cursor.execute(sql, (4, '马六')) # 元组格式数据 # 数据单独赋给一个对象 sql = "insert into username values(%s,%s)" data = (5, '老七') cursor.execute(sql, data) #sql和data之间以","隔开 sql = "insert into username values(%s,'%s')" data = (6, '小八') cursor.execute(sql % data) #sql和data之间以"%"隔开,此时它的sql中注意要给中文字符对应的占位符加上引号,即"%s",不然会报错:unsupported format character conn.commit() # 提交,不然无法保存插入或者修改的数据(这个一定不要忘记加上) cursor.close() # 关闭游标 conn.close() # 关闭连接
-
change the data
After execution of modification statements must be executed
.commit()
to commit the transaction, you can modify the uniform submitted after more than otherwise操作无效
import pymysql # 连接数据库 conn = pymysql.connect( host='127.0.0.1', user='root', passwd='root', port=3306, db='test', charset='utf8' ) # 创建一个游标 cursor = conn.cursor() # 修改数据 sql = "update username set name='%s' where id=%s" #注意%s什么时候加引号,什么时候不加 data = ('改名了', 1) cursor.execute(sql % data) sql = "update username set name=%s where id=%s" data = ('也改名了', 2) cursor.execute(sql, data) conn.commit() # 提交,不然无法保存插入或者修改的数据 cursor.close() # 关闭游标 conn.close() # 关闭连接
-
delete data
After execute delete statement must execute
.commit()
commit a transaction, you can remove the Unified submit after more than otherwise操作无效
import pymysql # 连接数据库 conn = pymysql.connect( host='127.0.0.1', user='root', passwd='root', port=3306, db='test', charset='utf8' ) # 创建一个游标 cursor = conn.cursor() # 删除数据 sql = "delete from username where id=%s" data = (2) cursor.execute(sql, data) conn.commit() # 提交,不然删除操作不生效 cursor.close() # 关闭游标 conn.close() # 关闭连接