Python与MySQL交互创建包含字段有id,姓名,班级名称,家庭住址,请使用mysqldb连接到数据库
时间: 2024-10-09 07:13:47 浏览: 49
mysql_read.rar_Python MySQLdb_connect_python
Python与MySQL交互通常需要使用`mysql-connector-python`库,也就是`pymysql`或更推荐的`mysql-connector-python-c`版本,它提供了一个简单的方式来操作MySQL数据库。以下是使用`pymysql`创建包含`id`, `姓名`, `班级名称`, 和 `家庭住址` 字段的基本步骤:
```python
import pymysql
# 连接到MySQL数据库
def connect_to_mysql():
# 数据库配置信息
host = 'your_host'
user = 'your_username'
password = 'your_password'
db_name = 'your_database'
# 创建连接
connection = pymysql.connect(host=host,
user=user,
password=password,
database=db_name)
return connection
# 创建表
def create_table(connection):
cursor = connection.cursor()
sql_query = """
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
class_name VARCHAR(50),
address VARCHAR(200)
);
"""
try:
cursor.execute(sql_query)
print("Table created successfully.")
except Exception as e:
print(f"Error creating table: {e}")
connection.commit()
# 示例连接并创建表
if __name__ == "__main__":
conn = connect_to_mysql()
create_table(conn)
conn.close()
阅读全文