更新时间:2025-09-27 12:18点击:55
创建数据库前我们也可以使用 "SHOW DATABASES" 语句来查看数据库是否存在:
cursor.execute("SHOW DATABASES")
for x in cursor:
if x['Database']=='test':
print("数据库test已存在")
创建数据库
CREATE DATABASE test
# 检查表是否存在sqlite3
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='your_table_name';")
if cursor.fetchone() is not None:
# 检查表是否存在,使用MySQLdb或pymysql
cursor.execute("SHOW TABLES LIKE 'your_table_name'")
if cursor.fetchone():
print("表存在")
#查看test数据库中所有表,也可判断users表是否存在
cursor.execute("show tables")
for x in cursor:
if x['Tables_in_test']=='users':
print("数据库test中users表已存在")
如果表存在则删除
DROP TABLE IF EXISTS EMPLOYEE
使用预处理语句创建表
sql = """CREATE TABLE EMPLOYEE \
( \
FIRST_NAME CHAR(20) NOT NULL, \
LAST_NAME CHAR(20), \
AGE INT, \
SEX CHAR(1), \
INCOME FLOAT \
)"""
查看表格的结构
sql="desc users"
cursor.execute(sql)
data=cursor.fetchall()
print(data)
# SQL 插入语句
sql = "INSERT INTO users(name, age, occupation) VALUES (%s, %s, %s)"\
%('"longg"','"33"','"jdjdjdjlonggggg"')
#批量插入使用 executemany() 方法,该方法的第二个参数是一个元组列表
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = [
('Google', 'https://www.google.com'),
('Github', 'https://www.github.com'),
('Taobao', 'https://www.taobao.com'),
('stackoverflow', 'https://www.stackoverflow.com/')
]
mycursor.executemany(sql, val)
mydb.commit() # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")
数据记录插入后,获取该记录的 ID
print("1 条记录已插入, ID:", mycursor.lastrowid)
查看表中的数据:select * from table_name;
查看表中的数据并限制数量:select * from table_name limit number;比如select * from table_name limit 10;
也可以指定起始位置,使用的关键字是 OFFSET:
mycursor.execute("SELECT * FROM sites LIMIT 3 OFFSET 1") # 0 为 第一条,1 为第二条,以此类推
如果我们只想读取一条数据,可以使用 fetchone() 方法:
主键设置ALTER TABLE 来给表添加主键
mycursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
创建 sites 表,给表创建主键。
mycursor.execute("CREATE TABLE sites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), url VARCHAR(255))")
排序可以使用 ORDER BY 语句,默认的排序方式为升序,关键字为 ASC,如果要设置降序排序,可以设置关键字 DESC。
删除记录使用 "DELETE FROM" 语句:
sql = "DELETE FROM sites WHERE name = 'stackoverflow'"
数据表更新使用 "UPDATE" 语句:
UPDATE `web80`.`cms_data` SET `content` = '' WHERE `dataid` = 1941
UPDATE `web80`.`cms_show` SET `intro` = '' WHERE `id` = 1924