PyMySQL 示例

2022-03-21 11:14 更新

以下示例使用以下數(shù)據(jù)表結(jié)構(gòu)


CREATE TABLE users(
    id int(11) NOT NULL AUTO_INCREMENT,
    email varchar(255) COLLATE utf8_bin NOT NULL,
    password varchar(255) COLLATE utf8_bin NOT NULL,
    PRIMARY KEY (`id`)
	) 
	ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
	AUTO_INCREMENT=1 ;

對這個表進行進行CRUD操作


import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

這個例子將打印:

{'password': 'very-secret', 'id': 1}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號