1. 安装PyMySQL
$ pip install pymysql
github地址
2. select操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import pymysql connection = pymysql.connect( host="localhost", port = 3306, user = "root", password = "root", db = "test", charset = "utf8" ) cur = connection.cursor() cur.execute("select * from test") res = cur.fetchall() for row in res: print (row) connection.close() val = input("press any key to exit ...")
|
3. insert操作
1 2 3 4 5 6
| with connection.cursor() as cur: sql = "insert into test(id, name, age, description) values(11,'tony',%s,%s)" cur.execute(sql, (30, "this is description to tony ...")) connection.commit()
|
4. 错误处理