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, ('[email protected]', '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, ('[email protected]',))
        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()

你可能感兴趣的:(pythonmysql)