赞
踩
Python可以使用多种库来操作MySQL和SQL Server数据库,比较常用的是pymysql、
mySQLdb和pyodbc
。这里我将给出三个例子,分别展示如何使用这两种库进行基本的增删改查操作。
pymysql
操作MySQL数据库:首先,你需要安装pymysql
库,可以通过pip进行安装:
pip install pymysql
以下是使用pymysql
进行增删改查的例子:
- import pymysql
-
- # 创建连接
- conn = pymysql.connect(host='localhost', user='root', password='password', db='testdb')
-
- # 创建游标
- cursor = conn.cursor()
-
- # 增:插入数据
- sql = "INSERT INTO students(name, age) VALUES ('%s', '%d')" % ('Tom', 20)
- try:
- # 执行sql语句
- cursor.execute(sql)
- # 提交到数据库执行
- conn.commit()
- except:
- # 如果发生错误则回滚
- conn.rollback()
-
- # 删:删除数据
- sql = "DELETE FROM students WHERE age > '%d'" % (20)
- try:
- # 执行sql语句
- cursor.execute(sql)
- # 提交到数据库执行
- conn.commit()
- except:
- # 如果发生错误则回滚
- conn.rollback()
-
- # 改:更新数据
- sql = "UPDATE students SET age = '%d' WHERE name = '%s'" % (21, 'Tom')
- try:
- # 执行sql语句
- cursor.execute(sql)
- # 提交到数据库执行
- conn.commit()
- except:
- # 如果发生错误则回滚
- conn.rollback()
-
- # 查:查询数据
- sql = "SELECT * FROM students"
- try:
- # 执行sql语句
- cursor.execute(sql)
- # 获取所有记录列表
- results = cursor.fetchall()
- for row in results:
- print(row)
- except:
- print("Error: unable to fetch data")
-
- # 关闭连接
- cursor.close()
- conn.close()

以下是使用mySQLdb进行增删改查的例子:
- import MySQLdb
-
- # 连接到MySQL数据库
- conn = MySQLdb.connect(host='localhost', user='root', password='password', db='mydatabase')
-
- # 创建游标对象
- cursor = conn.cursor()
-
- # 插入数据
- sql = "INSERT INTO mytable (name, age) VALUES (%s, %s)"
- data = ('John', 25)
- cursor.execute(sql, data)
-
- # 更新数据
- sql = "UPDATE mytable SET age = %s WHERE name = %s"
- data = (26, 'John')
- cursor.execute(sql, data)
-
- # 查询数据
- sql = "SELECT * FROM mytable"
- cursor.execute(sql)
- result = cursor.fetchall()
- for row in result:
- print(row)
-
- # 删除数据
- sql = "DELETE FROM mytable WHERE name = %s"
- data = ('John',)
- cursor.execute(sql, data)
-
- # 关闭游标和连接
- cursor.close()
- conn.close()

pyodbc
操作SQL Server数据库:首先,你需要安装pyodbc
库,可以通过pip进行安装:
pip install pyodbc
以下是使用pyodbc
进行增删改查的例子:
- import pyodbc
-
- # 创建数据库连接
- conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=user;PWD=password')
-
- # 创建游标
- cursor = conn.cursor()
-
- # 增:插入数据
- sql = """INSERT INTO students (name, age)
- VALUES (?, ?)"""
- cursor.execute(sql, ('Tom', 20))
- conn.commit()
-
- # 删:删除数据
- sql = """DELETE FROM students WHERE age > ?"""
- cursor.execute(sql, (20,))
- conn.commit()
-
- # 改:更新数据
- sql = """UPDATE students SET age = ? WHERE name = ?"""
- cursor.execute(sql, (21, 'Tom'))
- conn.commit()
-
- # 查:查询数据
- sql = """SELECT * FROM students"""
- cursor.execute(sql)
- rows = cursor.fetchall()
- for row in rows:
- print(row)
-
- # 关闭连接
- cursor.close()
- conn.close()

以上代码仅供参考,具体的操作方式可能会因库的版本、数据库的配置等而有所不同。请根据实际情况进行调整。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。