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

发布于 2024-09-29 11:02:48 字数 334 浏览 0 评论 0原文

我有多个名称为 "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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

莳間冲淡了誓言ζ 2024-10-06 11:02:48

没问题。 Python 有几个第三方库可以连接到数据库。但是,如果您只需要执行一次此操作,最简单的方法是使用一个 Python 脚本,将 SQL 指令写入 stdout:

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

然后只需从 CLI 中调用它,如下所示:

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

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:

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

Then just call it from CLI like this:

./sqlgenscript.py | mysql -u username -p
温柔少女心 2024-10-06 11:02:48

是的,它是可能的,您可以使用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

末が日狂欢 2024-10-06 11:02:48

我认为您可以创建一个带有一个参数的例程,并将“i”作为参数发送到您的例程中。然后你就可以调用你的例程了。

调用testMy_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,...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文