简体   繁体   English

可以以编程方式更改多个MySQL表吗?

[英]Possible to programmatically ALTER multiple MySQL tables?

I have multiple MySQL tables with names of the form "Shard_0", "Shard_1", "Shard_2" ... "Shard_n" All of them have identical table structure. 我有多个MySQL表,这些表的名称形式为"Shard_0", "Shard_1", "Shard_2" ... "Shard_n"所有这些表均具有相同的表结构。 They all live in the same database. 它们都生活在同一个数据库中。

Say I want to add a column to all those tables. 假设我要向所有这些表添加一列。 Is there a way to do that programmatically? 有没有办法通过编程方式做到这一点?

Something like: 就像是:

# pseudo code    
for i in range(n):
    tablename = "shard_"+str(i)
    ALTER TABLE tablename ...

Is it possible to do something like that? 可以做这样的事情吗? If so what language and/or library do I need? 如果是这样,我需要什么语言和/或图书馆?

Thanks 谢谢

No problem. 没问题。 Python has several third party libraries to connect to a db. Python有几个第三方库可以连接到数据库。 But the simplest approach if you have to do this for just one time would be a python script that writes the SQL instructions just to stdout: 但是,最简单的方法(如果只需要执行一次)将是一个python脚本,该脚本仅将SQL指令写入stdout:

for i in range(n):
    tablename = "shard_"+str(i)
    print 'ALTER TABLE tablename ...'

Then just call it from CLI like this: 然后像这样从CLI调用它:

./sqlgenscript.py | mysql -u username -p

Yes its possible, you can use MySqlDb module for python and write the queries similar to sql queries and execute them to update the tables. 是的,它是可能的,您可以将MySqlDb模块用于python并编写类似于sql查询的查询,并执行它们以更新表。 Have a look at this: http://mysql-python.sourceforge.net/MySQLdb.html 看看这个: http : //mysql-python.sourceforge.net/MySQLdb.html

I think you can create a routine which takes one argument, and send "i" as argument to your routine. 我认为您可以创建一个接受一个参数的例程,然后将“ i”作为参数发送到您的例程。 Then you can call your routine. 然后,您可以调用例程。

Call test . 通话test My_Alter (i); My_Alter (i);

where i=1,2,3,... 其中i = 1,2,3,...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM