安装 pymsql
1 pip install pymysql
执行mysql的相关操作
1 import pymysql 2 3 #添加数据 4 5 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘‘, db=‘yyy‘) 6 7 cursor = conn.cursor() #更改获取数据结果的数据类型,默认是元组,可以改为字典等:conn.cursor(cursor=pymysql.cursors.DictCursor) 8 9 10 # sql = """CREATE TABLE EMPLOYEE ( 11 # FIRST_NAME CHAR(20) NOT NULL, 12 # LAST_NAME CHAR(20), 13 # AGE INT, 14 # SEX CHAR(1), 15 # INCOME FLOAT )""" 16 # 17 # cursor.execute(sql) 18 19 #row_affected = cursor.execute("create table t1(id INT ,name VARCHAR(20))") 20 21 #row_affected=cursor.execute("INSERT INTO t1(id,name) values (1,‘alvin‘),(2,‘xialv‘)") 22 23 #cursor.execute("update t1 set name = ‘silv2‘ where id=2") 24 25 26 27 28 #查询数据 29 row_affected=cursor.execute("select * from t1") 30 one=cursor.fetchone() 31 32 # many=cursor.fetchmany(2) 33 # all=cursor.fetchall() 34 35 36 37 #scroll 38 #cursor.scroll(-1,mode=‘relative‘) # 相对当前位置移动 39 40 #cursor.scroll(2,mode=‘absolute‘) # 相对绝对位置移动 41 #三个关闭连接 46 conn.commit() 47 cursor.close() 48 conn.close()
自已测试完的代码
1 #先执行安装mymtsql 命令 pip install pymysql 2 import pymysql 3 4 conn = pymysql.connect(host=‘127.0.0.1‘,port=3306,user = ‘root‘, passwd = ‘123123‘,db = ‘test‘) 5 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor); #获取一个游标 如果后面不加参数则表示以列表的方式显示出来 6 sql = ‘select * from user‘ 7 8 row = cursor.execute(sql) #执行sql语句 9 one = cursor.fetchone() #取出执行完的值 10 #cursor.scroll(-1,mode = ‘relative‘) # 相对当前位置移动 11 cursor.scroll(2,mode=‘absolute‘) # 相对绝对位置移动 12 one1 = cursor.fetchone() 13 print(one,one1) 14 15 conn.commit() 16 cursor.close() 17 conn.close()