首页 > 编程知识 正文

Python保存数据库数据的方法

时间:2023-11-21 02:54:05 阅读:299035 作者:AYTR

在本文中,我们将详细介绍如何使用Python保存数据库数据。我们将从以下几个方面来进行阐述:

一、连接到数据库

在保存数据库数据之前,我们首先需要连接到要保存的数据库。Python提供了多种数据库连接模块,其中最常用的是sqlite3mysql.connector。下面是连接到SQLite数据库和MySQL数据库的示例代码:

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('test.db')

import mysql.connector

# 连接到MySQL数据库
conn = mysql.connector.connect(
  host="localhost",
  user="user",
  password="password",
  database="database"
)

二、创建数据表

在将数据保存到数据库之前,我们需要在数据库中创建相应的数据表。下面是使用sqlite3mysql.connector创建数据表的示例代码:

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('test.db')

# 创建数据表
conn.execute('''CREATE TABLE IF NOT EXISTS students
             (ID INT PRIMARY KEY     NOT NULL,
             NAME           TEXT    NOT NULL,
             AGE            INT     NOT NULL,
             GRADE          INT     NOT NULL);''')

import mysql.connector

# 连接到MySQL数据库
conn = mysql.connector.connect(
  host="localhost",
  user="user",
  password="password",
  database="database"
)

# 创建数据表
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS students (ID INT, NAME VARCHAR(255), AGE INT, GRADE INT)")

三、保存数据

一旦数据库和数据表创建完成,我们可以使用Python保存数据到数据库中。下面是将数据保存到SQLite数据库和MySQL数据库的示例代码:

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('test.db')

# 插入数据
conn.execute("INSERT INTO students (ID, NAME, AGE, GRADE) VALUES (1, 'Tom', 18, 90)")
conn.execute("INSERT INTO students (ID, NAME, AGE, GRADE) VALUES (2, 'Mary', 17, 95)")
conn.commit()

import mysql.connector

# 连接到MySQL数据库
conn = mysql.connector.connect(
  host="localhost",
  user="user",
  password="password",
  database="database"
)

# 插入数据
cursor = conn.cursor()
cursor.execute("INSERT INTO students (ID, NAME, AGE, GRADE) VALUES (1, 'Tom', 18, 90)")
cursor.execute("INSERT INTO students (ID, NAME, AGE, GRADE) VALUES (2, 'Mary', 17, 95)")
conn.commit()

四、查询数据

除了保存数据,我们还可以使用Python从数据库中查询数据。下面是从SQLite数据库和MySQL数据库中查询数据的示例代码:

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('test.db')

# 查询数据
cursor = conn.execute("SELECT ID, NAME, AGE, GRADE from students")
for row in cursor:
   print("ID = ", row[0])
   print("NAME = ", row[1])
   print("AGE = ", row[2])
   print("GRADE = ", row[3])

import mysql.connector

# 连接到MySQL数据库
conn = mysql.connector.connect(
  host="localhost",
  user="user",
  password="password",
  database="database"
)

# 查询数据
cursor = conn.cursor()
cursor.execute("SELECT ID, NAME, AGE, GRADE FROM students")
result = cursor.fetchall()
for row in result:
   print("ID = ", row[0])
   print("NAME = ", row[1])
   print("AGE = ", row[2])
   print("GRADE = ", row[3])

五、关闭数据库连接

在使用完数据库后,我们需要关闭数据库连接以释放资源。下面是关闭SQLite数据库和MySQL数据库连接的示例代码:

import sqlite3

# 关闭SQLite数据库连接
conn.close()

import mysql.connector

# 关闭MySQL数据库连接
conn.close()

通过以上步骤,我们可以使用Python连接到数据库,并保存、查询数据。这为我们在开发过程中提供了便利。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。