python——mysql与python交互

2018-06-08  本文已影响9人  Jalynn葸
sudo apt-get  install python-mysqldb
image.png
Connection 对象
Cursor对象
增加

安装pymysql的方法
https://blog.csdn.net/medivhq/article/details/73831386

import pymysql
try:
    conn = pymysql.connect(host='localhost', user='root', passwd='xjx', db='epoque', port=3306, charset='utf8')
    cur = conn.cursor()
    sql = 'insert into students(name) values("LiMing")'
    cur.execute(sql)
    conn.commit()
    cur.close()
    conn.close()
except Exception as e:
    print(e)
sql语句参数化
import pymysql
try:
    conn = pymysql.connect(host='localhost', user='root', passwd='xjx', db='epoque', port=3306, charset='utf8')
    cur = conn.cursor()
    # sql = 'delete from students where id>3'
    name = input("请输入用户名:")
    sql = 'insert into students(name) values(%s)'
    cur.execute(sql, [name])
    conn.commit()
    cur.close()
    conn.close()
    print('ok')
except Exception as e:
    print(e)
上一篇下一篇

猜你喜欢

热点阅读