美文网首页
pymysql例子

pymysql例子

作者: lucasdada | 来源:发表于2017-12-26 11:39 被阅读0次

The following examples make use of a simple table

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 ;
import pymysql.cursors

#连接到数据库
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # 新建一个记录
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    #连接不会被自动提交,所以必须调用提交来保存结果
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # 读取单一的记录
        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}

相关文章

网友评论

      本文标题:pymysql例子

      本文链接:https://www.haomeiwen.com/subject/kpvdgxtx.html