pymysql模块用法
python关于mysql的API--pymysql模块
pymsql是Python中操作MySQL的模块,其使用方法和py2的MySQLdb几乎相同。
模块安装
1
|
pip install pymysql |
执行sql语句
import pymysql #添加数据 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='yyy') cursor = conn.cursor() # sql = """CREATE TABLE EMPLOYEE ( # FIRST_NAME CHAR(20) NOT NULL, # LAST_NAME CHAR(20), # AGE INT, # SEX CHAR(1), # INCOME FLOAT )""" # # cursor.execute(sql) #row_affected = cursor.execute("create table t1(id INT ,name VARCHAR(20))") #row_affected=cursor.execute("INSERT INTO t1(id,name) values (1,'alvin'),(2,'xialv')") #cursor.execute("update t1 set name = 'silv2' where id=2") #查询数据 row_affected=cursor.execute("select * from t1") one=cursor.fetchone() # many=cursor.fetchmany(2) # all=cursor.fetchall() #scroll #cursor.scroll(-1,mode='relative') # 相对当前位置移动 (备注:参数:1是向下,-1是向上) #cursor.scroll(2,mode='absolute') # 相对绝对位置移动 #更改获取数据结果的数据类型,默认是元组,可以改为字典等:conn.cursor(cursor=pymysql.cursors.DictCursor) conn.commit() cursor.close() conn.close()
示例:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='oldboy123', db='s1')
# cursor = conn.cursor()
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#用赋值的方式查看
# sql="create table kuaiwei(id int,name varchar(20));"
#
# cursor.execute(sql)
#执行命令,反回结果
# ret=cursor.execute("insert into kuaiwei VALUES (1,'linye')")
#
# print(ret)
ret=cursor.execute("select * from kuaiwei")
# print(cursor.fetchone())
# print(cursor.fetchall())
print(cursor.fetchmany(3))
#相对当前位置移动,-1是向上
# cursor.scroll(-1,mode="relative")
#相对当前位置移动,1是向下
# cursor.scroll(1,mode="relative")
#absolute 相对绝对位置移动
# cursor.scroll(1,mode="absolute")
# print(cursor.fetchone())
conn.commit()
cursor.close()
conn.close()
#mysql数据库
mysql> select * from kuaiwei;
+------+-------+
| id | name |
+------+-------+
| 1 | alex |
| 2 | alvin |
| 1 | linye |
+------+-------+
3 rows in set (0.00 sec)