Pymysql Python connection MySQL insert usage

From Red Zebra, 1 Year ago, written in Python, viewed 227 times.
URL https://pastebin.vip/view/4a7996ca
  1. import pymysql
  2.  
  3.  
  4. def main():
  5.     no = int(input('编号: '))
  6.     name = input('名字: ')
  7.     loc = input('所在地: ')
  8.     # 1. 创建数据库连接对象
  9.     con = pymysql.connect(host='localhost', port=3306,
  10.                           database='hrs', charset='utf8',
  11.                           user='yourname', password='yourpass')
  12.     try:
  13.         # 2. 通过连接对象获取游标
  14.         with con.cursor() as cursor:
  15.             # 3. 通过游标执行SQL并获得执行结果
  16.             result = cursor.execute(
  17.                 'insert into tb_dept values (%s, %s, %s)',
  18.                 (no, name, loc)
  19.             )
  20.         if result == 1:
  21.             print('添加成功!')
  22.         # 4. 操作成功提交事务
  23.         con.commit()
  24.     finally:
  25.         # 5. 关闭连接释放资源
  26.         con.close()
  27.  
  28.  
  29. if __name__ == '__main__':
  30.     main()
  31.  

Reply to "Pymysql Python connection MySQL insert usage"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website