一、在终端安装数据库模块:
sudo pip3 install pymysql
二、在.py文件中导入pymysql模块
from pymysql import *
三、创建连接对象
conn = connect(host="localhost", port=3306, user="用户名", password="密码", database="数据库名", charset="utf8")
四、创建游标对象
cursor = conn.cursor()
五、execute执行sql语句
sql = "增、删、改、查 语句"
cursor.execute(sql)
cursor.execute("select * from goods")
# 生效的行数,游标中存储的是信息。
# 取查询的结果
cursor.fetchone() # 执行一次fetchone()显示游标中的一条记录
cursor.fetchmany()
cursor.fetchall() # 显示游标中除当前显示过的剩余的全部记录
"""
备注:
1、增删改查语句都要放在execute(" ")中执行。
2、执行完增、删、改命令后一定要提交(conn.commit())
3、在
"""
六、关闭
关闭游标
cursor.close()
–关闭连接对象
conn.close()
注意:一定要先关闭游标,在关闭连接对象
案例:增、删、改、查
from pymysql import *
def main():
# 1、创建Connection连接
conn = connect(host='localhost',port=3306,user='root',password='root',database='jing_dong',charset='utf8')
# 2、获得Cursor对象
cursor = conn.cursor()
# 3、查询
find_name = input("请输入物品名称:")
# 非安全的方式 (sql注入问题)
# 输入 " or 1=1 or " (双引号也要输入)
# sql = """select * from goods where name="%s" """ % find_name
# print("""sql===>%s<====""" % sql)
# 执行select语句,并返回受影响的行数:查询所有数据
# count = cursor.execute(sql)
# 安全的方式 (简单避免sql注入问题)
# 构造参数列表
params = [find_name]
# 执行select语句,并返回受影响的行数:查询所有数据
count = cs1.execute('select * from goods where name=%s', params)
"""
注意:
如果要是有多个参数,需要进行参数化
那么params = [值1, 值2....],此时sql语句中有多个%s即可
"""
# 打印受影响的行数
print("查询到%d条数据:" % count)
# 遍历显示查询到的记录
for i in range(count):
# 获取查询的结果
result = cursor.fetchone()
# 打印查询的结果
print(result)
# 4、增、删、改
# (1)增加
count = cs1.execute('insert into goods_cates(name) values("硬盘")')
# 打印受影响的行数
print(count)
count = cs1.execute('insert into goods_cates(name) values("光盘")')
print(count)
# (2)更新
# count = cs1.execute('update goods_cates set name="机械硬盘" where name="硬盘"')
# (3)删除
# count = cs1.execute('delete from goods_cates where id=6')
# (4)提交之前的操作,可以执行多次增、删、改语句,最后提交
conn.commit()
# 关闭Cursor对象
cs1.close()
conn.close()
if __name__ == '__main__':
main()