python连接数据库需要使用到pymysql模块
import pymysql
conn = pymysql.connect(host = '127.0.0.1', port = 3306, user = 'root', passwd = 'root', db = 'pymysql')
# 不填写参数的情况下,查询返回的结果为元组形式
# cursor = conn.cursor()
# 返回字典需要添加此参数,cursor=pymysql.cursors.DictCursor
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 查询数据
r = cursor.execute('SELECT * FROM user')
# 返回查询到的条目数
print(r)
# 返回第一条数据
res = cursor.fetchone()
print(res)
# 从上一次游标结束的位置继续返回,返回第二条第三条数据
res = cursor.fetchmany(2)
print(res)
# 返回所有数据
res = cursor.fetchall()
print(res)
插入数据,在插入前检查是否已存在该条数据,注意变量放在元组中,更新表需要commit()才会生效
username = 'hello'
passwd = 'world'
r = cursor.execute("SELECT * FROM user WHERE username = %s", username)
if r == 0:
cursor.execute('INSERT INTO user(username, passwd) VALUES(%s, %s)', (username, passwd))
conn.commit()
print('创建成功')
else:
print('该用户已存在')
更新数据
username = 'hello'
new_passwd = 'china'
cursor.execute("UPDATE user SET passwd = %s WHERE username = %s", (new_passwd, username))
conn.commit()
删除数据
username = 'hello'
cursor.execute("DELETE FROM user WHERE username = %s", username)
conn.commit()