给我写一份python代码,连接我指定的mysql数据库,然后随机生成五个大写英文,你自己创建一个新表,录入数据库,并且要求随机生成的英文不能重复
时间: 2023-06-25 08:03:01 浏览: 37
好的,以下是代码:
```python
import mysql.connector
import random
import string
# 连接数据库
my_db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 定义一个生成随机字符串的函数
def random_string(length):
letters = string.ascii_uppercase
return ''.join(random.choice(letters) for i in range(length))
# 生成5个不重复的随机字符串
random_strings = set()
while len(random_strings) < 5:
random_strings.add(random_string(1))
# 将随机字符串插入到数据库中
my_cursor = my_db.cursor()
my_cursor.execute("CREATE TABLE IF NOT EXISTS random_strings (id INT AUTO_INCREMENT PRIMARY KEY, value VARCHAR(255))")
for string in random_strings:
sql = "INSERT INTO random_strings (value) VALUES (%s)"
val = (string,)
my_cursor.execute(sql, val)
my_db.commit()
# 关闭数据库连接
my_cursor.close()
my_db.close()
print("随机字符串已成功插入到数据库中!")
```
请将 `yourusername`、`yourpassword` 和 `yourdatabase` 替换成你自己的数据库用户名、密码和数据库名。