简体   繁体   English

使用 Python 在 SQL 中使用多个数据库

[英]Using multiple databases in SQL with Python

I'm working on a registration site and right now I am trying to make multiple bases at the same time.我正在注册网站上工作,现在我正在尝试同时制作多个基地。

I have 2 databases, one called Tables , and the other called Digit .我有 2 个数据库,一个称为Tables ,另一个称为Digit

I want to use the SAME function for both of them, only to manage 2 databases at the same time, differ by the front end choice.我想对它们使用 SAME 函数,只同时管理 2 个数据库,因前端选择而异。

I tried to use %s as a place holder for the table name, while i have a dict at the beginning for the different databases (1: Tables, 2 : Digit)我尝试使用 %s 作为表名的占位符,而我在开头有一个 dict 用于不同的数据库(1:表,2:数字)

cursor.execute("SELECT * FROM %s WHERE active = %s AND isFull = %s ORDER BY minLevel" , [bases[DB], 1,0])

This is the code I wrote, I was hoping to switch the databases based on the DB given from the front end of the site.这是我写的代码,我希望根据站点前端给出的数据库切换数据库。

And.. it didn't work.而且..它没有用。 I'm really stuck here, and I am not sure if this way is even legal...我真的被困在这里,我不确定这种方式是否合法......

Thanks a head for you help!谢谢大佬帮忙!

I figured it out!我想到了!

thanks to another post by the way - thank to cursor.query( 'select * from %s;', ('thistable',) ) throws syntax error 1064: ...near ' 'thistable' ' at顺便感谢另一篇文章 - 感谢cursor.query( 'select * from %s;', ('thistable',) ) 抛出语法错误 1064: ...near ''thistable' ' at

the problem is you cant use %s on "database variables", like column, databases, etc.问题是你不能在“数据库变量”上使用 %s,比如列、数据库等。

the way to work around it is to build the query as a string beforehand and then to use execute in this format : cursor.execute (q , [variable]) while q is the pre-built query.解决这个问题的方法是预先将查询构建为字符串,然后以这种格式使用 execute : cursor.execute (q , [variable])而 q 是预构建的查询。 and while building the query to add the database wanted并在构建查询以添加所需的数据库时

so the code above should look like (i have a pre built dictionary)所以上面的代码应该看起来像(我有一个预先构建的字典)

q= "SELECT * FROM " + dict[Number] + " WHERE active = %s AND isFull = %s ORDER BY minLevel"
cursor.execute(q , [1,0])

while dict is the name of the dictionary, number is the variable i got from the front end. dict 是字典的名字,number 是我从前端得到的变量。 and active , is Full and minLevel are columns of mine i use.和 active , is Full 和 minLevel 是我使用的列。

hope it will help somebody!希望它会帮助某人!

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

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