import pymysql.cursors from urllib.parse import urlparse
URI = 'mysql+pymysql://root:[email protected]:3306/study?charset=utf8mb4' URL_CONFIG = urlparse(URI)
conn = pymysql.connect( host = URL_CONFIG.hostname, port = URL_CONFIG.port, user = URL_CONFIG.username, password = URL_CONFIG.password, db = URL_CONFIG.path[1:], charset = 'utf8mb4', cursorclass = pymysql.cursors.DictCursor )
注意地址模式需要使用 mysql+pymysql
操作数据库
插入数据
1 2 3 4
cursor = conn.cursor() cursor.execute('insert into book (name) values (%s)', ['wxnacy']) conn.commit() cursor.close()
查询数据
1 2 3 4 5 6
cursor = conn.cursor() cursor.execute('select * from book where name = %s', ['wxnacy']) conn.commit() res = cursor.fetchall() cursor.close() print(res) # [{"id": 1, "name": "wxnacy"}]