python pymysql 创建表,如果不存在,则创建,如果存在,则跳过
时间: 2023-10-09 16:15:00 浏览: 106
可以使用以下代码来实现:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='password', database='test', charset='utf8mb4')
# 创建游标对象
cur = conn.cursor()
# 创建表格的SQL语句
sql = '''
CREATE TABLE IF NOT EXISTS `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`age` INT(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
'''
# 执行SQL语句
cur.execute(sql)
# 关闭游标和连接
cur.close()
conn.close()
```
在创建表格的SQL语句中,使用了`IF NOT EXISTS`来判断表格是否存在,如果不存在则创建表格,否则跳过。通过这种方式可以保证表格只会被创建一次。
相关问题
python将csv导入pymysql数据库
以下是Python将CSV导入pymysql数据库的示例代码:
```python
import csv
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='testdb')
# 创建游标
cur = conn.cursor()
# 读取CSV文件
with open('data.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
# 跳过第一行标题行
next(reader)
for row in reader:
# 将每一行数据插入到数据库中
cur.execute("INSERT INTO table_name (column1, column2, column3) VALUES (%s, %s, %s)", (row[0], row[1], row[2]))
# 提交事务
conn.commit()
# 关闭游标和连接
cur.close()
conn.close()
```
在以上示例代码中,我们首先连接了MySQL数据库,然后创建了一个游标。接着,我们使用Python内置的csv模块读取了一个名为data.csv的CSV文件,并将每一行数据插入到数据库表中。最后,我们提交了事务并关闭了游标和连接。注意,在插入数据时,我们使用了占位符来避免SQL注入攻击。
python 读取mysql数据库的每一张表格,给每张表格增加两列,列名称为a和b,数据类型为小数.,如果a和b列存在则跳过,并且使用多线程
可以使用Python中的多线程库`threading`来实现多线程读取MySQL数据库中的每一张表格,并给每张表格增加两列。
首先,需要安装Python的MySQL连接库`pymysql`,可以使用以下命令进行安装:
```python
pip install pymysql
```
然后,可以使用以下代码实现:
```python
import pymysql
import threading
# 定义数据库连接参数
db_config = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': '123456',
'database': 'mydb'
}
# 定义增加列的SQL语句
alter_sql = 'ALTER TABLE {} ADD COLUMN a DECIMAL(10, 2) DEFAULT 0.00, ADD COLUMN b DECIMAL(10, 2) DEFAULT 0.00'
# 定义线程类
class AddColumnThread(threading.Thread):
def __init__(self, table_name):
threading.Thread.__init__(self)
self.table_name = table_name
def run(self):
# 建立数据库连接
conn = pymysql.connect(**db_config)
cursor = conn.cursor()
# 判断表格是否已经存在a和b列
cursor.execute('DESCRIBE {}'.format(self.table_name))
columns = [col[0] for col in cursor.fetchall()]
if 'a' in columns and 'b' in columns:
print('Table {} already has column a and b'.format(self.table_name))
else:
# 增加列
cursor.execute(alter_sql.format(self.table_name))
print('Add column a and b to table {}'.format(self.table_name))
# 关闭数据库连接
cursor.close()
conn.close()
if __name__ == '__main__':
# 建立数据库连接
conn = pymysql.connect(**db_config)
cursor = conn.cursor()
# 获取所有表格的名称
cursor.execute('SHOW TABLES')
table_names = [table[0] for table in cursor.fetchall()]
# 关闭数据库连接
cursor.close()
conn.close()
# 创建线程并启动
threads = []
for table_name in table_names:
thread = AddColumnThread(table_name)
thread.start()
threads.append(thread)
# 等待所有线程执行完毕
for thread in threads:
thread.join()
```
上述代码会读取MySQL数据库中的每一张表格,并给每张表格增加两列,列名称为a和b,数据类型为小数。如果a和b列已经存在,则跳过该表格。同时,使用多线程可以加快处理速度。
需要注意的是,在多线程场景下,需要建立多个数据库连接,因此需要在每个线程中单独建立和关闭数据库连接,以免出现连接池满的情况。
阅读全文
相关推荐

















