import mysql.connector
# 连接到 MySQL 数据库
def connect_to_database():
try:
connection = mysql.connector.connect(
host='localhost', # 数据库主机地址
user='your_username', # 数据库用户名
password='your_password', # 数据库密码
database='your_database' # 要连接的数据库名称
)
if connection.is_connected():
print("成功连接到数据库")
return connection
except mysql.connector.Error as err:
print(f"连接失败: {err}")
return None
# 插入数据到表中
def insert_data(connection, table, data):
cursor = connection.cursor()
sql = f"INSERT INTO {table} (name, age) VALUES (%s, %s)"
cursor.execute(sql, data)
connection.commit()
print(f"插入数据: {data}")
# 查询数据
def query_data(connection, table):
cursor = connection.cursor()
sql = f"SELECT * FROM {table}"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
# 关闭数据库连接
def close_connection(connection):
if connection.is_connected():
connection.close()
print("数据库连接已关闭")
# 示例代码
if __name__ == "__main__":
conn = connect_to_database()
if conn:
# 插入示例数据
insert_data(conn, 'users', ('Alice', 30))
# 查询表中的数据
query_data(conn, 'users')
# 关闭连接
close_connection(conn)
mysql.connector.connect()
方法连接到 MySQL 数据库。需要提供主机地址、用户名、密码和数据库名称。INSERT INTO
SQL 语句将数据插入到指定表中,并使用 connection.commit()
提交事务。SELECT * FROM
SQL 语句查询表中的所有数据,并通过 cursor.fetchall()
获取结果集。上一篇:mysql四种索引类型
下一篇:mysql schema
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站