How to address MongoDB database with hyphen in name in Python? - python

I need to remove any element from a Mongo database when I have two databases:
mydatabase
data-test-second
With the first database this isn't a problem, I use MongoClient:
self.db = self.client.mydatabase
result = self.db.test.delete_one({"name": 'testelement'})
bBt when I use this for a second database I have a problem with:
self.db = self.client.data-test-second
underlining the database name, how I can write this? Or I can't use this solution for the second name?

In the case that your database name is not valid as an object name in Python, you need to address the database differently:
self.db = self.client["data-test-second"]
In general, it is probably advisable to always use this pattern.
For more information, you can refer to the documentation.

Related

Is it necessary to specify the database name in the code if the connection to the database is already established?

Let's say I make a request like:
query_select = "SELECT `client_id` FROM `my_databse_name`.`orders` ORDER BY `client_id` DESC"
await cursor.execute(query_select)
In this example, I append the database name to the table name (my_databse_name.orders) instead of just writing orders. Is this addition redundant?
Moreover, I've already installed the connection, and when I installed it, I specified the database name - my_databse_name.
I even checked if I remove that name and pass it like this:
query_select = "SELECT `client_id` FROM `orders` ORDER BY `client_id` DESC"
Then my call works correctly anyway. But in a lot of examples, I often see references to tables where the database name is added. Therefore, I'm not sure what should I do and also add. Although I would prefer to remove the database name from my queries.
The question is - does such adding a name affect the reliability of work, etc.?
I am using MySQL.

Selecting a column with a slash in SQL Alchemy

I need to select some columns from a table with SQL Alchemy. Everything works fine except selecting the one column with '/' in the name. My query looks like:
query = select([func.sum(Table.c.ColumnName),
func.sum(Table.c.Column/Name),
])
Obviously the issue comes from the second line with the column 'Column/Name'. Is there a way in SQL Alchemy to overcome special characters in a column name?
edit:
I've it all inside some class but simplified version of a process looks like this. I create an engine (all necessary db data is inside create_new_engine() function) and map all tables in db into metadata.
def map(self):
from sqlalchemy.engine.base import Engine
# check if engine exist
if not isinstance(self.engine, Engine):
self.create_new_engine()
self.metadata = MetaData({'schema': 'dbo'})
self.metadata.reflect(bind=self.engine)
Then I map a single table with:
def map_table(self, table_name):
table = "{schema}.{table_name}".format(schema=self.metadata.schema, table_name=table_name)
table = self.metadata.tables[table]
return table
In the end I use pandas read_sql_query to run above query with connection and engine established earlier.
I'm connecting to SQL Server.
Since Table.c points to a plain python obect. Try in pure Python
query = select([func.sum(Table.c.ColumnName),
func.sum(getattr(Table.c, 'Column/Name')),
])
So in your case (from comments above) :
func.sum(getattr(Table.c, 'cur/fees'))

How do I create a database with database name as variable using Python?

I am learning how to work with Python and MySQL. I wanted to know how can I create a database with it's name as variable using python. I have tried this but it does not work at all. I have used this method in insert query so thought it might work in this too.
db_query=('''CREATE DATABASE VALUES(?)''')
VALUES=email2
my_cursor.execute(db_query,VALUES)
mydb.commit()
The database name is not an expression that can be computed in MySQL, it has to be literal, so you can't use a placeholder or function call there.
If the database name is in a Python variable, use string formatting to substitute it.
email2 = 'desired_db_name`
db_query = f'CREATE DATABASE `{email2}`'
my_cursor.execute(db_query)
mydb.commit()
If the DB name comes from user input, make sure you validate it carefully first.

Pushing dataframe to postgres using sqlalchemy and psycogp2

I am trying to write dataframes to postgres . For that DBAPI used is psycogp2.
localconn='postgresql+psycopg2://postgres/PSWD#localhost:5432/localPG'
localEng=engine.create_engine(localconn)
df.to_sql("DUMMY", localEng)
But its throwing error (psycopg2.OperationalError) could not translate host name postgres to address: Name or service not known
localPG is the database name.
Where I am doing wrong?
The format you have written is wrong, use the following:
localEng = create_engine('postgresql+psycopg2://[user]:[pass]#[host]:[port]/[schema]', echo=False)
and of course, you should replace every parameter between the bracket with the equivalent database credentials.

Binding variable to table name with cx_Oracle

I'm using cx_Oracle in Python and can't get a variable be used as table name, like in this simple example:
query = "select * from some.:usertable.userinfo"
bindvars = {'usertable':usertable}
cursor.execute(query, bindvars)
What is the correct syntax? Variable substition works fine when I use WHERE… etc. but not with table names. I guess I have to separate ":usertable" somehow…
Database adapters rarely support using parameters for anything that isn't a 'value' (something that needs quoting). Either use string formatting (dodgy, you run the risk of a sql injection) or use a library like SQLAlchemy that let's you produce valid SQL using Python code.
If you are certain your usertable value is sane (checked against a list of existing table names, for example), the following would work:
query = 'select * from some.{usertable}.userinfo'.format(usertable=usertable)
You cannot bind an object name in Oracle, only a literal. Oracle does, however, have an inbuilt package dbms_assert, to help prevent SQL injection when using dynamic object names. The most useful function in your case is probably sql_object_name, which:
"... verifies that the input parameter string is a qualified SQL
identifier of an existing SQL object."
For instance you could do the following in cx_Oracle.
object_name = cursor.callfunc('sys.dbms_assert.sql_object_name'
, cx_Oracle.string, ['usertable'])
It raises ORA-44002, if the name is invalid, which you can capture in cx_Oracle, or if everything's fine continue as Martijn has suggested.
I would recommend reading Oracle's guide to guarding against SQL injection.
Perhaps it's a bit late to reply, but I was dealing with the same thing 2 days ago.
The solution is, as Martjin says, to format the query.
query = f'select * from {tableName}'
Hope it helps someone as it helped me.

Categories

Resources