python常用模块-pymysql数据库连接

python操作mysql比较简单,记住一句话就够了:

创建连接>>>新建游标对象 >>>执行sql语句 >>>事务提交>>> 结束连接.

 

1. 代码如下:

import pymysql
from data.pwd import mysql_pwd


# 新建连接
def main():
conn1=pymysql.connect(
host='127.0.0.1',
user='bernard',
passwd=mysql_pwd,
port= 3307,
db="school",
charset="utf8"
)
cursor = conn1.cursor() # 新建游标对象
sql1 = """select * from student where stuid = 1001"""
cursor.execute(sql1) # 执行sql语句
conn1.commit() #提交事务

sql2 = f"""select * from student where stuid >= 1001"""
cursor.execute(sql2)
data = cursor.fetchall() # 获取数据
for i in data:
print(i)
print(data)

cursor.close() # 关闭连接,关闭游标,关闭sql连接
conn1.close()

if __name__ == '__main__':
main()

------------------------------------------------------------------------------------------------------ 

2. 其中sql语句就是我们常用的各种增删改查等语句,而针对游标的方法有:

# 一次性获取一条数据
a = cursor.fetchone()
# 一次性获取所有数据
a = cursor.fetchall()
# 获取前三行
result = cursor.fetchmany(3)
# fetchall(),fetchmany(),fetchone()同时作用于同一个查询时,每个方法执行开头是上一个方法执行的结尾

cursor.excutemany(query, args)#执行多个数据库查询或命令
str_insert = "INSERT INTO Cu_table (id) VALUES (%s)"
cursor.executemany(str_insert,['A','B','C','D']) #一次插入A B C D 四个值

------------------------------------------------------------------------------------------------------------- 

3. 针对连接的方法有:

其实在创建连接时也可加入参数 autocommit=True 来使事务的自动提交。不用每次再重复提交。

出现错误时,记得conn.rollback().....

------------------------------------------------------------------------------------------------------

 

Now, try it! And maybe you will find something interesting...

 

posted @ 2021-03-01 22:55  沈一愣  阅读(110)  评论(0编辑  收藏  举报