python 对 mysql 操作

安装pymysql:

pip install pymysql

操作:

import pymysql as db

conn=db.connect(host='192.168.73.131',user='wzh',passwd='123456',port=3306,database='TestDB',charset='utf8')
cur=conn.cursor()

try:
    sql='insert into users(name,age) values(%s,%s)'
    cur.execute(sql,('张三',12))
    conn.commit()
    
    cur.execute('select * from users')
    result=cur.fetchall()
    for item in result:
        print(f'{item[1]}{item[2]}')
except:
    print('error')
    conn.rollback()
finally:
    cur.close()
    conn.close()
 
posted @ 2021-11-18 16:24  lunawzh  阅读(24)  评论(0编辑  收藏  举报