建立链接
import pymysql conn = pymysql.connect( host='localhost', user='root', password='1111111', port=3306, database='demo_pymysql' ) cursor = conn.cursor() res = cursor.execute('select * from user;') print(cursor.fetchall()) conn.close() 1234567891011121314
插入数据
import pymysql conn = pymysql.connect( host='localhost', user='root', password='22222', port=3306, database='demo_pymysql' ) cursor = conn.cursor() sql = """ insert into user(id, username, age, password) values(null, %s, %s, %s) """ username = 'dd' age = 21 password = '123123' cursor.execute(sql, (username, age, password)) conn.commit() # 注意需要coomit后才会插入 res = cursor.execute('select * from user;') print(cursor.fetchall()) conn.close()
1234567891011121314151617181920212223242526查找数据
使用pymysql查询数据。可以使用fetch方法
1、fetchone():这个方法每次获取一条数据
2、fetchall():这个方法接收全部的返回值
3、fetchmany():这个方法可以返回指定条数的数据
import pymysql conn = pymysql.connect( host='localhost', user='root', password='', port=3306, database='demo_pymysql' ) cursor = conn.cursor() sql = """ select username, age from user where id > 2; """ cursor.execute(sql) res = cursor.fetchmany(10) print(res) conn.close()
123456789101112131415161718删除数据
sql = """ delete from user where id=3 """ cursor.execute(sql) conn.commit() 12345
需要注意的是在执行删除语句后,需要commit才能生效
更新数据
sql = """ update user set username='luole' where id=1 """ cursor.execute(sql) conn.commit() 12345
需要注意的是在执行更新语句后,需要commit才能生效