Pymysql 连接 mysql与python

安装
pie install pymysql

连接,执行sql, 关闭
import pymysql


user = input('用户名:').strip()
password = input('密码:').strip()

连接
# get connection obj
conn = pymysql.connect(host='localhost', 
    port=3306, 
    user=user, 
    password= password, 
    database='multi_table', 
    charset='utf8') # 注意没有-,不要写utf-8

# get cursor 
cursor = conn.cursor() # it likes mysql> you input command here and execute

sql = 'select name, gender, age from employee where age>18 '

# 执行
result = cursor.execute(sql)
all_data = cursor.fetchall() # get all data in tuple format, you can only pick once 
many_data = cursor.fetchmany(3) # get 3 record once
one_data = cursor.fetchone() # get one record in tuple format, next time you get second record, 
cursor.scroll(3,'absolute') # move 3 step from initail position, next time start from 4
cursor.scroll(1, 'relative') # move 1 step from before position (from 4 to 5) next time get 5
cursor.close() 
conn.close()

不要自己手动拼接字符串,让pymysql拼接,pymysql 的execute方法
name = input('name:').strip()
password = input('passwor:').strip()

sql = "select * from userinfo where username=%s and password=%s;"
result = cursor.execute(sql, [name, password])

增删改查, commit()
conn = pymysql.connect(host='localhost', 
    port=3306, 
    user=user, 
    password= password, 
    database='multi_table', 
    charset='utf8') # 注意没有-,不要写utf-8
cursor = conn.cursor()


sql = "insert into userinfo(name, password) values('root', '123456');"
res = cursor.execute(sql)  # 返回执行sql影响成功的条数
print(cursor.lastrowid)  # 返回当前记录第多少条,即最后一条数据的自增id

插入多条 executemany
sql = "insert into userinfo(name, password) values(%s, %s);"
res = cursor.executemany(sql,['root','123'],('Jack':'123'),('lemon':'123')])

删除
sql = "Delete from userinfo where age >28"


更改:
res = cursor.execute("update userinfo set username='andy' where id='nopassword')

提交
conn.commit() # 注意是conn.commit, 提交后都会保存到数据库

关闭
cursor.close()
conn.close()

上一篇:pep8 规范

下一篇:mysql 逻辑查询语句的执行顺序