本文共 1622 字,大约阅读时间需要 5 分钟。
在 Python 开发中,MySQL 是一个常用的关系型数据库管理系统。通过 Python 与 MySQL 的交互,可以有效地实现数据库的 CRUD(创建、读取、更新、删除)操作。本文将介绍如何利用 Python 来操作 MySQL 数据库。
首先,需要建立与 MySQL 数据库的连接。可以通过 MySQLdb 库来实现。以下是一个典型的连接流程:
#!/usr/bin/python# -*- coding: utf-8 -*-import MySQLdbtry: # 连接数据库 conn = MySQLdb.connect( host='localhost', user='root', passwd='root', port=3306 ) # 获取数据库 cursor 对象 cur = conn.cursor() # 创建数据库(如果不存在) cur.execute('create database if not exists python') # 选择数据库 conn.select_db('python') # 创建表 cur.execute('create table test(id int, info varchar(20))') # 插入数据 values = [(i, 'hi rollen' + str(i)) for i in range(20)] cur.executemany('insert into test values (%s, %s)', values) # 更新操作 cur.execute('update test set info="I am rollen" where id=3') # 提交事务 conn.commit() # 关闭 cursor cur.close() # 关闭连接 conn.close()except MySQLdb.Error as e: print("Mysql Error %d: %s" % (e.args[0], e.args[1])) commit():提交事务。rollback():回滚事务。cursor():获取数据库 cursor 对象,为执行SQL 命令提供方法。callproc(self, procname, args):执行存储过程,返回受影响的行数。execute(self, query, args):执行单条 SQL 语句。executemany(self, query, args):执行单条 SQL 语句,但重复执行参数列表中的参数。fetchall(self):获取所有返回结果行。fetchmany(self, size=None):获取指定数量的返回结果行。fetchone(self):获取一条返回结果行。scroll(self, value, mode='relative'):移动指针到指定的行。通过以上代码,可以实现以下功能:
这种方法适合开发者在日常项目中快速操作数据库,简化了数据库交互的复杂性。
在 Python 开发中,通过 MySQLdb 库,可以轻松实现对 MySQL 数据库的操作。通过合理使用 cursor 对象的方法,可以高效完成 CRUD 操作。记住,数据库操作需要谨慎处理事务,确保数据的准确性和一致性。
转载地址:http://msofk.baihongyu.com/