使用PYMYSQL向MySQL数据表中插入一条数据
import pymysql
def add_data():
'''添加一条数据'''
# 链接本地的mysql数据库
db = pymysql.connect(host="localhost", user="root", password="请输入自己的数据库密码",
port=3306, db="warehousing", charset="utf8")
# 创建游标
cursor = db.cursor()
sql = '''
INSERT INTO student (fullname,sex,age,
numberId,birthday,grade,
iphone,address) VALUES ("张三",
"男",18,123456,"20230404",
"五年级","15081099256","地球"
)
'''
try:
# 执行sql语句
cursor.execute(sql)
db.commit() # 完成操作后提交操作
print("数据插入成功!")
except Exception as e:
db.rollback() # 发生错误时使用事务回滚
print("数据插入失败!case %s" % e)
finally:
cursor.close()
db.close()
if __name__ == "__main__":
add_data()
程序运行结果
数据插入成功!
Process finished with exit code 0