原标題:Python MySQL 資料庫連接配接池元件
frompymysqlpool importConnectionPool config = { 'pool_name': 'test', 'host': 'localhost', 'port': 3306, 'user': 'root', 'password': 'root', 'database': 'test'} defconnection_pool():# Return a connection pool instancepool = ConnectionPool(**config) pool.connect() returnpool # 直接通路并擷取一個 cursor 對象,自動 commit 模式會在這種方式下啟用withconnection_pool().cursor() ascursor: print('Truncate table user') cursor.execute('TRUNCATE user') print('Insert one record') result = cursor.execute('INSERT INTO user (name, age) VALUES (%s, %s)', ('Jerry', 20)) print(result, cursor.lastrowid) print('Insert multiple records') users = [(name, age) forname in['Jacky', 'Mary', 'Micheal'] forage inrange(10, 15)] result = cursor.executemany('INSERT INTO user (name, age) VALUES (%s, %s)', users) print(result) print('View items in table user') cursor.execute('SELECT * FROM user') foruser incursor: print(user) print('Update the name of one user in the table') cursor.execute('UPDATE user SET name="Chris", age=29 WHERE id = 16') cursor.execute('SELECT * FROM user ORDER BY id DESC LIMIT 1') print(cursor.fetchone()) print('Delete the last record') cursor.execute('DELETE FROM user WHERE id = 16')傳回搜狐,檢視更多
責任編輯: