欢迎访问宙启技术站
智能推送

如何使用Python函数连接和操作数据库

发布时间:2023-06-17 21:40:51

Python是一种高级编程语言,它可以使用各种数据源进行数据处理。在数据处理中,数据库是非常重要的一部分,因为它可以帮助我们存储、管理和查找大量数据。本文将介绍如何使用Python函数连接和操作数据库。

1. 连接数据库

在Python中,连接数据库是使用数据库API来操作的。常用的数据库API有Python DB-API和SQLAlchemy。在此我们以Python DB-API为例,Python DB-API是Python标准化接口,它可以让Python与不同的数据库通信。使用Python DB-API连接数据库可以分为以下几个步骤:

1)导入数据库API模块

不同的数据库API有不同的模块名,所以根据不同的模块名导入相应的模块。

例如,要连接MySQL数据库,可以在Python程序中导入Python MySQL connector模块:

import mysql.connector

2)建立数据库连接

在导入数据库API模块后,需要通过API提供的连接函数与数据库进行连接。

以MySQL为例,可以使用该模块提供的connection()函数来建立连接:

mydb = mysql.connector.connect(
    host="localhost",
    user="username",
    password="password",
    database="mydatabase"
)

根据需要,需要修改host、user、password和database来连接正确的数据库。

3)获取数据库游标

连接建立后,需要获取游标才能执行SQL语句。可以使用connection对象提供的cursor()方法来获取游标:

mycursor = mydb.cursor()

4)关闭连接

连接建立后需要关闭连接,可以使用connection对象提供的close()方法来关闭连接:

mydb.close()

2. 数据库查询

在Python中连接到数据库后可以执行各种类型的SQL查询语句。Python使用execute()方法来执行SQL查询。下面是查询示例:

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="username",
    password="password",
    database="mydatabase"
)

mycursor = mydb.cursor()

# 查询所有数据
mycursor.execute("SELECT * FROM customers")

# 查询结果
myresult = mycursor.fetchall()

for x in myresult:
    print(x)

# 关闭连接
mydb.close()

3. 数据库插入

在Python中将数据插入数据库是使用INSERT INTO语句。Python中使用execute()方法将数据插入到数据库。下面是插入数据的示例:

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="username",
    password="password",
    database="mydatabase"
)

mycursor = mydb.cursor()

# 插入数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)

# 数据库提交
mydb.commit()

print(mycursor.rowcount, "record inserted.")

4. 数据库删除

在Python中,删除数据库数据是使用DELETE FROM语句。在Python中使用execute()方法删除数据库数据。下面是删除数据的示例:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="username",
  password="password",
  database="mydatabase"
)

mycursor = mydb.cursor()

# 删除数据
sql = "DELETE FROM customers WHERE address = 'Hrwegweg'"
mycursor.execute(sql)

# 数据库提交
mydb.commit()

print(mycursor.rowcount, "record(s) deleted")

5. 数据库更新

在Python中,使用UPDATE语句来更新数据库数据。在Python中使用execute()方法更新数据库数据。下面是更新数据的示例:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="username",
  password="password",
  database="mydatabase"
)

mycursor = mydb.cursor()

# 更新数据
sql = "UPDATE customers SET address = %s WHERE address = %s"
val = ("Canyon 123", "Highway 21")
mycursor.execute(sql, val)

# 数据库提交
mydb.commit()

print(mycursor.rowcount, "record(s) updated")

以上就是Python函数连接和操作数据库的基本内容,通过以上示例,可以更清楚地了解Python操作数据库的基本方法。 这些技巧都可应用于各种不同类型的关系数据库,包括MySQL、SQL Server、Oracle等。