获取查询数据
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', db='studydb')
cursor = conn.cursor()
cursor.execute('select * from student WHERE stu_id>%s and name=%s', (3, 'alex'))
row_1 = cursor.fetchone()
row_3 = cursor.fetchmany(3)
row_a = cursor.fetchall()
print(row_1, row_3, row_a)
conn.commit()
cursor.close()
conn.close()
插入数据
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',passwd='', db='studydb')
cursor = conn.cursor()
cursor.executemany('insert into student(name,age,register_date)VALUES (%s,%s,%s)',
[('eric', 20, '2016-5-24'), ('eric', 20, '2016-5-24')])
conn.commit()
cursor.close()
conn.close()
fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', db='studydb')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute('select * from student WHERE stu_id>%s', (3,))
row = cursor.fetchall()
print(row)
conn.commit()
cursor.close()
conn.close()