python数据库(python数据库有哪些)
Python数据库
简介:
Python可以操作多种数据库系统,包括SQLite、MySQL、PostgreSQL等。本文介绍了Python对数据库的常见操作方法,包括连接数据库、创建表、插入数据、查询数据等。
多级标题:
一、连接数据库
二、创建表
三、插入数据
四、查询数据
一、连接数据库
Python通过使用相应的模块,可以连接各种数据库。常用的模块有pymysql、sqlite3、psycopg2等。
以MySQL数据库为例,连接数据库的代码如下:
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='123456', db='test')
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# 关闭数据库连接
db.close()
上述代码中,host指定要连接的主机名、user和password指定连接的用户与密码、db指定操作的数据库名称。通过调用cursor()方法创建一个游标对象用于我们执行SQL语句。
二、创建表
连接数据库之后,我们可以在其中创建表。使用CREATE TABLE语句创建表,结构如下:
CREATE TABLE table_name(
column1 datatype constraint,
column2 datatype constraint,
.....
columnN datatype constraint,
PRIMARY KEY (one or more columns)
);
其中,table_name为表的名称,column1, column2, ...., columnN为表的列名,datatype为数据类型,constraint为约束条件,PRIMARY KEY为表的主键。
如果需要创建名为students的表,可以使用如下代码:
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='123456', db='test')
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# 创建名为students的表
sql = '''CREATE TABLE students(
id INT NOT NULL AUTO_INCREMENT,
name CHAR(20) NOT NULL,
age INT,
PRIMARY KEY (id)
)'''
cursor.execute(sql) # 执行SQL语句
# 关闭数据库连接
db.close()
上述代码中,我们通过CREATE TABLE语句创建了一个名为students的表,该表包含三个列:id、name、age。
三、插入数据
在创建表之后,可以向其中插入数据。使用INSERT INTO语句插入数据,结构如下:
INSERT INTO table_name (column1, column2, column3, ...,columnN) VALUES (value1, value2, value3, ...,valueN);
如果需要向students表中插入一条记录,可以使用如下代码:
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='123456', db='test')
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# 向students表中插入一条记录
sql = "INSERT INTO students(name, age) VALUES (%s, %s)"
val = ("张三", 18)
cursor.execute(sql, val) # 执行SQL语句
# 提交到数据库执行
db.commit()
# 关闭数据库连接
db.close()
上述代码中,我们使用INSERT INTO语句向students表中插入了一条记录。
四、查询数据
在插入数据之后,可以从表中查询数据。使用SELECT语句查询数据,结构如下:
SELECT column1, column2, column3, ..., columnN FROM table_name [WHERE Clause] [LIMIT N];
如果需要从students表中查询所有数据,可以使用如下代码:
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='123456', db='test')
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# 查询students表中所有数据
sql = "SELECT * FROM students"
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
age = row[2]
print("id=%d, name=%s, age=%d" % (id, name, age))
# 关闭数据库连接
db.close()
上述代码中,我们使用SELECT语句查询students表中所有数据,并按照id、name、age的顺序打印出来。
总结:
Python可以轻松处理多种数据库操作,如连接数据库、创建表、插入数据、查询数据等。通过以上介绍,希望读者能够掌握Python的数据库操作方法,为后续开发提供帮助。