本篇内容主要讲解“python怎么操作pymysql数据库”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“python怎么操作pymysql数据库”吧!
pip install pymysql
三种连接数据库的方式
import pymysql # 方式一 conn = pymysql.connect('localhost', 'root', 'root') # 方式二 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='', charset='utf8') # 方式三 config = { 'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'passwd': 'root', 'charset': 'utf8' } conn = pymysql.connect(**config)
创建一个test数据库并进入
import pymysql db = pymysql.connect("localhost", "root", "root", "test") # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() cursor.execute('DROP DATABASE IF EXISTS test') cursor.execute('CREATE DATABASE IF NOT EXISTS test') conn.select_db('test')
创建一张user表
import pymysql db = pymysql.connect("localhost", "root", "root", "test") cursor = db.cursor() cursor.execute('CREATE TABLE user(id int primary key,name varchar(30))')
import pymysql db = pymysql.connect("localhost", "root", "root", "test") cursor = db.cursor() try: # 执行SQL语句 sql = 'INSERT INTO user values("%d","%s")' %(1,"autofelix") cursor.execute(sql) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback() finally: # 关闭游标连接 cursor.close() # 关闭数据库连接 conn.close()
import pymysql db = pymysql.connect("localhost", "root", "root", "test") cursor = db.cursor() try: # 执行SQL语句 values = [(1, 'autofelix'), (2, '飞兔小哥')] cursor.executemany('INSERT INTO user values(%s,%s)', values) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback() finally: # 关闭游标连接 cursor.close() # 关闭数据库连接 conn.close()
import pymysql db = pymysql.connect("localhost", "root", "root", "test") cursor = db.cursor() count = cursor.execute('SELECT * FROM user') # 统计数据总数 print('total records: %d' %count) # 统计字段数 print('total records:', cursor.rowcount)
import pymysql db = pymysql.connect("localhost", "root", "root", "test") cursor = db.cursor() desc = cursor.description print("%s %3s" % (desc[0][0], desc[1][0]))
使用 fetchone 方法获取单条数据
import pymysql db = pymysql.connect("localhost", "root", "root", "test") cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法获取单条数据. data = cursor.fetchone() print("Database version : %s " % data) # 关闭数据库连接 db.close()
import pymysql db = pymysql.connect("localhost", "root", "root", "test") cursor = db.cursor() cursor.execute('SELECT * FROM user') results = cursor.fetchmany(5) for r in results: print (r)
import pymysql db = pymysql.connect("localhost", "root", "root", "test") cursor = db.cursor() cursor.execute('SELECT * FROM user') results = cursor.fetchall() for r in results: print (r)
每次都连接关闭很麻烦,使用上下文管理,简化连接过程
import pymysql import contextlib # 定义上下文管理器,连接后自动关闭连接 @contextlib.contextmanager def mysql(host='127.0.0.1', port=3306, user='root', passwd='', db='test',charset='utf8'): conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) try: yield cursor finally: conn.commit() cursor.close() conn.close() # 执行sql with mysql() as cursor: print(cursor) count = cursor.execute("select * from user") row_1 = cursor.fetchone() print row_count, row_1
到此,相信大家对“python怎么操作pymysql数据库”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。