Python管理mysql
基本操作
使用 pymysql库 来增加表、列、行和元素
增加表:
你可以使用 CREATE TABLE
SQL语句来创建一个新的表。
import pymysql
# 连接到数据库
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
db='your_db')
try:
with connection.cursor() as cursor:
# 创建表的SQL语句
create_table_sql = """
CREATE TABLE your_table_name (
id INT(11) NOT NULL AUTO_INCREMENT,
column1 VARCHAR(255),
column2 VARCHAR(255),
PRIMARY KEY (id)
)
"""
# 执行SQL语句
cursor.execute(create_table_sql)
finally:
# 关闭连接
connection.close()
增加列:
使用 ALTER TABLE
SQL语句来增加列。
import pymysql
# 连接到数据库
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
db='your_db')
try:
with connection.cursor() as cursor:
# 增加列的SQL语句
add_column_sql = """
ALTER TABLE your_table_name
ADD column3 VARCHAR(255)
"""
# 执行SQL语句
cursor.execute(add_column_sql)
finally:
# 关闭连接
connection.close()
增加行:
使用 INSERT INTO
SQL语句来增加行。
import pymysql
# 连接到数据库
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
db='your_db')
try:
with connection.cursor() as cursor:
# 插入数据的SQL语句
insert_data_sql = """
INSERT INTO your_table_name (column1, column2, column3)
VALUES ('value1', 'value2', 'value3')
"""
# 执行SQL语句
cursor.execute(insert_data_sql)
finally:
# 关闭连接
connection.close()
增加元素:
这通常意味着在行中添加更多的数据。你可以通过更新行数据来实现这一点。
使用 UPDATE
SQL语句来更新行数据。
import pymysql
# 连接到数据库
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
db='your_db')
try:
with connection.cursor() as cursor:
# 更新数据的SQL语句
update_data_sql = """
UPDATE your_table_name
SET column1 = 'new_value1', column2 = 'new_value2'
WHERE id = your_id
"""
# 执行SQL语句
cursor.execute(update_data_sql)
finally:
# 关闭连接
connection.close()