在Python中有很多需求都需要连接数据库来存储数据,接下来就一起来学习一下基础的Python 连接数据库语法吧!
1. 连接、关闭数据库
# 连接的函数
def getConnect():
conn = pymysql.Connect(host='',
user='root',
password='root',
database='productBase',
charset='utf8')
return conn
# 关闭的函数
def closeConnect(cursor,conn):
if cursor:
cursor.close()
print('已关闭cursor')
if conn:
conn.close()
print('已关闭conn')
2. 插入语句
# 插入数据insert
def insertData(sql):
conn = getConnect() # 获取连接
cursor = conn.cursor() # 创建游标
cursor.execute(sql) # 把语句放入游标
conn.commit() # 发送语句
closeConnect(cursor,conn) # 关闭连接
count = cursor.rowcount # 返回条目数
if count > 0:
return True
else:
return False
# 插入!! 使用format来插入变量
sql = "insert into tb_user(name,balance,age) value({},{},{})"/
.format(na

本文介绍了Python连接和操作数据库的基础语法,包括连接与关闭数据库、插入数据、查询数据、修改及删除数据。强调了连接数据库的重要性以及关闭数据库以避免服务崩溃的必要性。还指出游标在涉及数据更改时的作用。
最低0.47元/天 解锁文章
440

被折叠的 条评论
为什么被折叠?



