unable to set db using string while coding in python - mongodb

I would like to know if there is a way to set db using a variable
For example: I am coding in Python, and I connect using client = MongoClient(uri). All goes fine.
There are 4 dbs: test1,test2,test3,test4.
I am able to list them all.
dblist = client.list_database_names()
print(dblist)
All goes fine.
Now, Instead of connecting/ using
db = client.test1
Is there a way to use a string rather than actual name of the db?
such as str = 'test1', and then db=client.str.
(this doesn't work)
In my program , I display the list of dbs first and then I am taking user input on the db , and proceed with further flow, but unable to do so.
Please help.

You cannot add string as an name when it comes to that. However there is another function that takes string of the name of certain database and gets the database.
db=client.get_database('test')
Here is the documentation: https://api.mongodb.com/python/current/api/pymongo/mongo_client.html

Related

Why are identical SQL calls behaving differently?

I'm working on a web app in Rust. I'm using Tokio Postgres, Rocket and Tera (this may be relevant).
I'm using the following to connect to my DB which doesn't fail in either case.
(sql_cli, connection) = match tokio_postgres::connect("postgresql://postgres:*my_password*#localhost:8127/*AppName*", NoTls).await{
Ok((sql_cli, connection)) => (sql_cli, connection),
Err(e) => return Err(Redirect::to(uri!(error_display(MyError::new("Failed to make SQLClient").details)))),
};
My query is as follows. I keep my queries in a separate file (I'm self taught and find that easier).
let query= sql_cli.query(mycharactersquery::get_characters(user_id).as_str(), &[]).await.unwrap();
The get characters is as follows. It takes a user ID and should return the characters that they have made in the past.
pub fn get_characters(user_id: i16) -> String {
format!("SELECT * FROM player_characters WHERE user_id = {} ORDER BY char_id ASC;", user_id)
}
In my main file, I have one GET which is /mycharacters/<user_id> which works. This GET returns an HTML file. I have another GET which is /<user_id> which returns a Tera template. The first works fine and loads the characters, the second doesn't: it just loads indefinitely. I initially thought this was to do my lack of familiarity with Tera.
After some troubleshooting, I put some printouts in my code, the one before and after the SQL call work in /mycharacters/<user_id>, but only the one before writes to the terminal in /<user_id>. This makes me think that Tera isn't the issue as it isn't making it past the SQL call.
I've found exactly where it is going wrong, but I don't know why as it isn't giving an error.
Could someone please let me know if there is something obvious that I am missing or provide some assistance?
P.S. The database only has 3 columns, so an actual timeout isn't the cause.
I expected both of these SQL calls to function as I am connected to my database properly and the call is copied from the working call.

operator does not exist: # timestamp without time zone

In a parameterized query issued from c# code to PostgreSQL 10.14 via dotConnect 7.7.832 .NET connector, I select either a parameter value or the local timestamp, if the parameter is NULL:
using (var cmd = new PgSqlCommand("select COALESCE(#eventTime, LOCALTIMESTAMP)", connection)
When executed, this statement throws the error in subject. If I comment out the corresponding parameter
cmd.Parameters.Add("#eventTime", PgSqlType.TimeStamp).Value = DateTime.Now;
and hardcode
using (var cmd = new PgSqlCommand("select COALESCE('11/6/2020 2:36:58 PM', LOCALTIMESTAMP)", connection)
or if I cast the parameter
using (var cmd = new PgSqlCommand("select COALESCE(cast(#eventTime as timestamp without time zone), LOCALTIMESTAMP)", connection)
then it works. Can anyone explain what # operator in the error is referring to and why the error?
In the case that doesn't work, your .Net connection library seems to be passing an SQL command containing a literal # to the database, rather than substituting it. The database assumes you are trying to use # as a user defined operator, as it doesn't know what else it could possibly be. But no such operator has been defined.
Why is it doing that? I have no idea. That is a question about your .Net connection library, not about PostgreSQL itself, so you might want to add tag.
The error message you get from the database should include the text of the query it received (as opposed to the text you think it was sent) and it is often useful to see that in situations like this. If that text is not present in the client's error message (some connection libraries do not faithfully pass this info along) you should be able to pull it directly from the PostgreSQL server's log file.

In Grafana, how do I use a variable I made and give it as a value into a query search for a graph?

I am trying to take the value of a drop down I created in grafana, utilizing a query variable.
I am using SimpleJSON for my database.
I have tried this pattern where:
var is my variable that makes up the drop down menu
func is my function call for the database query that creates the graph
So then I wrote:
f.g.func[$var]
I get a Internal Server Error yet when I call func in kdb+ with the values directly, it works fine. So I think I'm passing in var incorrectly.
For grafana/kdb+ adaptor, the syntax is f.g.func["$var"]-- my above attempt lacks the quotes necessary

Search for MongoDB records containing a certain string

I have a MongoDB database full of tweets that I've gathered using the tweepy API, and I want to be able to search on a web application a hashtag and it shows the tweets containing that hashtag.
Currently, I have created a list with the DB records in, and iterating through that list to display them all, but now I want to refine the search so the user can choose what they see. I have the users search saved into a variable and I have tried the following ideas, but none seem to be working.
My first idea was to just pass in the variable and hope for the best
def display():
input = request.form['input'] # setting variable for user input
# Set up Mongo Client
client = MongoClient("mongo.user/pass")
# Accessing database
db = client.tweets
# acessing a collection
posts = db.posts
data = list(posts.find(input))
return render_template('results.html', posts_info=data)
With this, I get a TypeError, which I somewhat expected as I didn't expect it to be this easy
After some reading online, I tried using a regex.
def display():
input = request.form['input'] # setting variable for user input
# Set up Mongo Client
client = MongoClient("mongo.user/pass")
# Accessing database
db = client.tweets
# acessing a collection
posts = db.posts
data = list(posts.find({Tweet: {$regex: input}}))
return render_template('results.html', posts_info=data)
This also didn't work so I tried to hard code the regex to see if it was the user input variable creating issues
def display():
input = request.form['input'] # setting variable for user input
# Set up Mongo Client
client = MongoClient("mongo.user/pass")
# Accessing database
db = client.tweets
# acessing a collection
posts = db.posts
data = list(posts.find({Tweet: {$regex: "GoT"}}))
return render_template('results.html', posts_info=data)
With both these methods, I get syntax errors at the start of the regex expression, and flags the $ before regex
Error message that I get reads:
File "pathToWebApp/webApp.py", line 71
data = list(posts.find({Tweet: {$regex: input}}))
^
SyntaxError: invalid syntax
I've never worked with MongoDB or used regexs so I'm at a complete loss here. I've scoured the mongo docs but nothing I've tried works so any help from anyone would be greatly appreciated
By the looks of it you might need to wrap the $regex key in quotes as well:
data = list(posts.find({Tweet: {"$regex": input}}))

Preparing a command with Structured Parameters

I have this ADO.NET command object and I can set some parameters and execute it successfully.
_mergecommand.Parameters.Add(new SqlParameter("values", SqlDbType.Structured));
_mergecommand.Parameters["values"].TypeName = "strlist";
_mergecommand.Parameters["values"].Direction = ParameterDirection.Input;
_mergecommand.Parameters["values"].Value = valuelist;
_mergecommand.ExecuteNonQuery();
This works fine. But I want to prepare this command before executing it because I need to run this millions of times. I am using SQL Server 2008. I get this error if I try to prepare it
SqlCommand.Prepare method requires all variable length parameters to have an explicitly set non-zero Size.
Any idea how to do this?
This is old, but there does appear to be a correct answer which is to use -1 as the size, e.g.:
_mergecommand.Parameters.Add(new SqlParameter("values", SqlDbType.Structured, -1));
If you have to do it millions of times using a command like this is probably not a good strategy.
Can you serialize your data into an XML string and pass that as a single argument? That will be considerably less load on your network and SQL Server.... although it will probably hit your client a lot harder.
If you are dead set on doing it that way, maybe what you are looking for is an overload of the SqlCommand.Parameters.Add method:
_mergecommand.Parameters.Add("#values", System.Data.SqlDbType.NVarChar, 100).Value = foo;
is that more like what you wanted?