【问题标题】:Template for MySQL Table Creation - PythonMySQL 表创建模板 - Python
【发布时间】:2017-11-29 22:07:39
【问题描述】:

我在我的数据库中为每个用户创建一个表,然后存储特定于该用户的数据。由于我有 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"
)

【问题讨论】:

  • 我相信我找到了在 Python 中使用 format() 函数的解决方案。最后!它有效!
  • 除非你有很好的理由为每个用户创建一个表,否则我建议你改变你的设计。简单地创建一个用户表通常要容易得多
  • 我希望您传递给format() 的任何值都不是来自用户本身。如果是这样,您很容易受到SQL injection 的攻击。
  • @Chris 我希望在每个公司/用户的每个表中将每周的 InternalUsers 数量存储为单独的行,然后使用这些数据在一个漂亮的 UI 中绘制 InternalUsers 的增加/减少。所有数据都来自离线预先创建的 Excel 工作表。这都是服务器端。我想在每一行中存储 InternalUser 编号的列表,就好像一行是用户一样。但是,我似乎无法创建并稍后添加到 mySQL 中的列表。

标签: python mysql database-connection mysql-python


【解决方案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;

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

【讨论】:

  • 就在最近,我和我的上级讨论了我的用例。他给出的正是这个想法!你读心术,我亲爱的朋友。
猜你喜欢
  • 2011-10-11
  • 2014-08-02
  • 1970-01-01
  • 2020-04-04
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多