实现数据库的连接、库和表的创建与删除、数据的添加、删除、查询与修改
时间: 2023-08-07 17:08:16 浏览: 48
好的,以下是一个简单的 Python 示例来演示如何连接数据库、创建库和表、以及对数据进行增删改查操作。
首先,需要安装 Python 的 mysql-connector-python 库来连接 MySQL 数据库。在命令行中输入以下命令进行安装:
```
pip install mysql-connector-python
```
然后,可以使用以下代码连接到 MySQL 数据库:
```python
import mysql.connector
# 连接 MySQL 数据库
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='your_host', database='your_database')
```
其中,your_username 是 MySQL 数据库的用户名,your_password 是密码,your_host 是主机名或 IP 地址,your_database 是要连接的数据库名称。
接下来,可以使用以下代码创建一个新的数据库:
```python
# 创建数据库
cursor = cnx.cursor()
cursor.execute("CREATE DATABASE mydatabase")
```
可以使用以下代码列出所有数据库:
```python
# 列出所有数据库
cursor.execute("SHOW DATABASES")
for db in cursor:
print(db)
```
接着,可以使用以下代码连接到新创建的数据库:
```python
# 连接到新创建的数据库
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='your_host', database='mydatabase')
```
然后,可以使用以下代码创建一个新的表:
```python
# 创建表
cursor = cnx.cursor()
cursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
```
可以使用以下代码列出所有表:
```python
# 列出所有表
cursor.execute("SHOW TABLES")
for table in cursor:
print(table)
```
接下来,可以使用以下代码向表中添加数据:
```python
# 添加数据
cursor = cnx.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
cursor.execute(sql, val)
cnx.commit()
print(cursor.rowcount, "record inserted.")
```
可以使用以下代码查询表中的数据:
```python
# 查询数据
cursor = cnx.cursor()
cursor.execute("SELECT * FROM customers")
result = cursor.fetchall()
for row in result:
print(row)
```
最后,可以使用以下代码更新表中的数据:
```python
# 更新数据
cursor = cnx.cursor()
sql = "UPDATE customers SET address = %s WHERE name = %s"
val = ("Canyon 123", "John")
cursor.execute(sql, val)
cnx.commit()
print(cursor.rowcount, "record(s) affected")
```
可以使用以下代码删除表中的数据:
```python
# 删除数据
cursor = cnx.cursor()
sql = "DELETE FROM customers WHERE name = %s"
val = ("John", )
cursor.execute(sql, val)
cnx.commit()
print(cursor.rowcount, "record(s) deleted")
```
最后,需要关闭数据库连接:
```python
# 关闭数据库连接
cnx.close()
```
注意,以上代码仅供参考,实际使用时需要根据具体情况进行修改。