可以以编程方式更改多个 MySQL 表吗?
我有多个名称为 "Shard_0"、"Shard_1"、"Shard_2" ... "Shard_n"
形式的 MySQL 表,它们都具有相同的表结构。它们都位于同一个数据库中。
假设我想向所有这些表添加一列。有没有办法以编程方式做到这一点?
比如:
# pseudo code
for i in range(n):
tablename = "shard_"+str(i)
ALTER TABLE tablename ...
可以做这样的事情吗?如果是这样,我需要什么语言和/或库?
谢谢
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. 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没问题。 Python 有几个第三方库可以连接到数据库。但是,如果您只需要执行一次此操作,最简单的方法是使用一个 Python 脚本,将 SQL 指令写入 stdout:
然后只需从 CLI 中调用它,如下所示:
No problem. Python has several third party libraries to connect to a db. 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:
Then just call it from CLI like this:
是的,它是可能的,您可以使用Python的MySqlDb模块并编写类似于sql查询的查询并执行它们来更新表。看看这个: http://mysql-python.sourceforge.net/MySQLdb.html
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. Have a look at this: http://mysql-python.sourceforge.net/MySQLdb.html
我认为您可以创建一个带有一个参数的例程,并将“i”作为参数发送到您的例程中。然后你就可以调用你的例程了。
调用
test
。My_Alter
(i);其中 i=1,2,3,...
I think you can create a routine which takes one argument, and send "i" as argument to your routine. Then you can call your routine.
Call
test
.My_Alter
(i);where i=1,2,3,...