pymysql操作数据库

Posted 岁月峥嵘走过

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pymysql操作数据库相关的知识,希望对你有一定的参考价值。

import pymysql.cursors

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

with connection:
    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)

from pymysql import connect


# 创建Connection连接
conn = connect(host=\'localhost\',port=3306,database=\'df\',user=\'root\',password=\'mysql\',charset=\'utf8\')
# 获得Cursor对象
curson = conn.cursor()

count = curson.execute(\'select * from goods;\');
print(\'查询到%d条数据\'%count)
print(curson.fetchone())
#打印一条
print(curson.fetchmany())
#元祖里面包的元祖,就一条数据
print(curson.fetchmany(3))
#传参数,传几取几条
print(curson.fetchall())
#全部取

line_count = curson.fetchone()
print(line_count)
print(line_count[0])
print(line_count[1])
print(line_count[2])
#可以把一条语句里面的东西,一段一段的取出来


# 关闭Cursor对象
curson.close()
# 关闭Connection对象
conn.close()

以上是关于pymysql操作数据库的主要内容,如果未能解决你的问题,请参考以下文章

数据库可视化和pymysql模块

Python中pymysql基本使用

PyMySQL的使用详解

数据库操作 pymysql 封装处理(中级)

Python数据库编程pymysql

pymysql模块操作数据库与mysql数据备份