- pymysql是通过python实现的mysql客户端库,支持python3,用于代替mysqldb;
import pymysql
conn = pymsql.connect(host = ‘localhost’, port = 3306, user = ‘root’, password = ‘xxxx’, database = database_name, charset = utf8)
cursor = conn.cursor() – 获取游标
sql = ‘select * from table_name;’ – 要执行的sql语句
row_count = cursor.execute(sql) – 调用execute函数执行sql语句,返回值为sql语句在执行过程中影响的行数
print(‘sql语句执行影响的行数%d’ % row_count)
–插入数据
sql1 = ‘insert into user values(%s, %s);’
data1 = (5, ‘马超’)
cursor.execute(sql1, data1)
–修改数据
sql2 = ‘update user set user_name = %s where user_id = %s;’
data2 = (‘黄忠’, 4)
cursor.execute(sql2, data2)
–删除数据
sql3 = ‘delete from user where user_id = %s;’
data3 = 3
cursor.execute(sql3, data3)
conn.commit() --增删改后都需要提交
sql = ‘select * from user;’ – 要执行的sql语句
row_count = cursor.execute(sql) – 调用execute函数来执行sql语句,返回sql语句在执行过程中影响的行数
print(‘sql语句在执行过程中影响的行数%d’ % row_count)
for i in range(row_count):
print(cursor.fetchone()) # fetchone()取出结果集中的一行
–也可以使用下面的方法遍历
for line in cursor.fetchall():
print(line)
cursor.close()
conn.close()