用于MySQL表创建的模板 - Python

时间:2017-06-26 23:56:17

标签: python mysql database-connection mysql-python

我在数据库中为每个用户创建一个表,然后存储特定于该用户的数据。由于我有100多个用户,我希望在我的Python代码中自动化表创建过程。

就像我如何自动化表格中的行插入一样,我试图自动化表格插入 行插入代码:

PAYLOAD_TEMPLATE = (
    "INSERT INTO metadata "
    "(to_date, customer_name, subdomain, internal_users)"
    "VALUES (%s, %s, %s, %s)"
)

我如何使用

connection = mysql.connector.connect(**config)
cursor = connection.cursor()
# Opening csv table to feed data
with open('/csv-table-path', 'r') as weeklyInsight:
    reader = csv.DictReader(weeklyInsight)
    for dataDict in reader:
        # Changing date to %m/%d/%Y format
        to_date = dataDict['To'][:5] + "20" + dataDict['To'][5:]
        payload_data = (
            datetime.strptime(to_date, '%m/%d/%Y'),
            dataDict['CustomerName'],
            dataDict['Subdomain'],
            dataDict['InternalUsers']
        )
        cursor.execute(PAYLOAD_TEMPLATE, payload_data)

如何创建可以类似方式执行的'TABLE_TEMPLATE'来创建表格?

我希望创建它,以便在用其他字段替换某些字段后,可以从cursor执行模板代码。

TABLE_TEMPLATE = (
    "  CREATE TABLE '{customer_name}' (" # Change customer_name for new table 
    "'To' DATE NOT NULL,"
    "'Users' INT(11) NOT NULL,"
    "'Valid' VARCHAR(3) NOT NULL"
    ") ENGINE=InnoDB"
)

2 个答案:

答案 0 :(得分:1)

没有技术¹需要为每个客户创建一个单独的表。拥有单个表格更简单,更清晰,例如

-- A simple users table; you probably already have something like this
create table users (
  id integer not null auto_increment,
  name varchar(50),

  primary key (id)
);

create table weekly_numbers (
  id integer not null auto_increment,

  -- By referring to the id column of our users table we link each
  -- row with a user
  user_id integer references users(id),

  `date` date not null,
  user_count integer(11) not null,

  primary key (id)
);

让我们添加一些示例数据:

insert into users (id, name)
values (1, 'Kirk'),
  (2, 'Picard');

insert into weekly_numbers (user_id, `date`, user_count)
values (1, '2017-06-13', 5),
  (1, '2017-06-20', 7),
  (2, '2017-06-13', 3),
  (1, '2017-06-27', 10),
  (2, '2017-06-27', 9),
  (2, '2017-06-20', 12);

现在让我们看看柯克船长的号码:

select `date`, user_count
from weekly_numbers

-- By filtering on user_id we can see one user's numbers
where user_id = 1
order by `date` asc;

¹可能存在将客户数据分开的业务原因。一个常见的用例是隔离客户的数据,但在这种情况下,每个客户端的单独数据库似乎更合适。

答案 1 :(得分:0)

也许这就是您想要的模板:

customer_name = "WHO"

cursor.execute(""
    " CREATE TABLE `%s` ( "      
    " `To` DATE NOT NULL,"
    "'Users` INT(11) NOT NULL,"
    "`Valid` VARCHAR(3) NOT NULL"
    ") ENGINE=InnoDB"
      "" % (customer_name))

它使用customer_name的名称创建TABLE,但结构相同。