一 安装及导入
1. pip3 install pymysql
2. 安装完需要把包的路径加到Pycharm的路径中
二 执行SQL语句
import pymysql # create connection connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='test', charset="utf8") # create cursor cursor = connection.cursor() # execute statement cursor.execute('insert into tb1(nid,name) values(3, "Howard")') #cursor.execute('insert into tb1(nid,name) values(4, %s), input') 可以进行字符串拼接传参数,不能通过字符串拼接后传递变量的形式,不安全
#execute many statements
value = ( (5,'Paul'), (6, 'Wade') )
cursor.executemany('insert into tb1(nid,name) values(%s,%s), value)
# commit statemnet connection.commit()
# display info 不用commit
cursor.execute('select * from tb1')
result = cursor.fetchall()
#result = cursor.fetchone()
#result = cursor.fetchmany(size)
print(result)
# close cursor
cursor.close()
# close connection connection.close()
执行插入语句后的结果:
在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
- cursor.scroll(1,mode='relative') # 相对当前位置移动一行
- cursor.scroll(1,mode='absolute') # 相对绝对位置移动一 行
b. 另一种创建cursor
1 import pymysql 2 3 # create connection 4 connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='test', charset="utf8") 5 6 # create cursor 7 #cursor = connection.cursor() 8 cursor = connection.cursor(cursor=pymysql.cursors.DictCursor) 9 # execute statement 10 cursor.execute('select * from tb1') 11 print(cursor.fetchall()) 12 #commit statemnet 13 # connection.commit() 14 15 #close connection 16 connection.close()
执行结果:
可以看出是字典,这样就可以通过key, value的形式拿到每一个值了,比元祖更好用。
c.获取新创建的自增ID
id = cursor.lastrowid() #拿最后一条的id