登录
首页 >  数据库 >  MySQL

pymysql操作数据库

来源:SegmentFault

时间:2023-02-20 20:30:17 270浏览 收藏

有志者,事竟成!如果你在学习数据库,那么本文《pymysql操作数据库》,就很适合你!文章讲解的知识点主要包括MySQL、python,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

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操作数据库》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表