Usually I connect to a database in Pymongo like this:
# connect to the MongoDB
connection = MongoClient("mongodb://127.0.0.1:27017")
# connect to the database
self.db = self.connection.my_database
The problem is, the name of my_database always changes. How can I use a variable to choose the database?
Based on this documentation we can do it like this:
# connect to the MongoDB
connection = MongoClient("mongodb://127.0.0.1:27017")
# connect to the database
a = 'my_database'
self.db = self.connection[a]
Related
`db = MySQLdb.connect(
host = '12.34.567.891',
user = 'root',
passwd = '',
db = 'testdb',
port = "something-that-works")`
Very Simple Can I somehow make it so that it connects only to the ip '12.34.567.891'. Google is forwarding the port to 80 but you can't request port 80 or it ends up in an endless loop.
port=null or port = none will cause and error.
I have no issues connecting from my cli mysql client
Thank you,
I expected to be able to connect to the server no issues if I am able to do so from my cli - I need some way to send the connecting request to the raw IP no port. It may be possible python-mysql can't do this
3306 is the default MySQL port and it seems that you are using MySQL, so that should work. https://cloud.google.com/sql/docs/mysql/connect-overview
You will have an easier time connecting with the Cloud SQL Python Connector a library built purely for connecting to Cloud SQL with Python.
Looks like this:
from google.cloud.sql.connector import Connector
# build connection
def getconn() -> pymysql.connections.Connection:
with Connector() as connector:
conn = connector.connect(
"project:region:instance", # Cloud SQL instance connection name
"pymysql",
user="my-user",
password="my-password",
db="my-db-name"
)
return conn
# create connection pool
pool = sqlalchemy.create_engine(
"mysql+pymysql://",
creator=getconn,
)
# insert statement
insert_stmt = sqlalchemy.text(
"INSERT INTO my_table (id, title) VALUES (:id, :title)",
)
# interact with Cloud SQL database using connection pool
with pool.connect() as db_conn:
# insert into database
db_conn.execute(insert_stmt, id="book1", title="Book One")
# query database
result = db_conn.execute("SELECT * from my_table").fetchall()
# Do something with the results
for row in result:
print(row)
I need to connect to the ms-sql database and then create a new database there using python script.
I have the user credentials for the login. So how to create the connection to the ms-sql server using python.
If you do not have database name then use the connection string as mentioned in the code below. Create a database after connection and use the database finally.
import pyodbc
# if you have user id and password then try with this connection string
connection_string = f"DRIVER={SQL Server};SERVER={server_name};UID={user_id};PWD={password}"
# if using in the local system then use the following connection string
connection_string = f"DRIVER={SQL Server};SERVER={server_name}; Trusted_Connection=True;"
connection= pyodbc.connect(connection_string)
cursor = connection.cursor()
sql_create_database = f"CREATE DATABASE {database_name}"
cursor.execute(sql_create_database)
set_database = f"USE {database_name}"
cursor.execute(set_database)
According to documentation, parameters needed to connect to HANA database are host, port, user and password.
from hdbcli import dbapi
conn = dbapi.connect(
address="<hostname>",
port=3<NN>MM,
user="<username>",
password="<password>"
)
cursor = conn.cursor()
This selects username as schema by default. Is there a way to specify schema name?
AFAIK there is no connection property that would allow setting/switching to a specific schema.
What you can easily do, however, is to switch to your intended schema right after creating the connection:
conn = dbapi.connect(
address = 'hxehost',
port = '39013', # connecting to the HANA system, not the DB directly
user = '...',
password = '...',
databasename = 'HXE', # using the DB name instead of a port number
#key='USER1UserKey', # address, port, user and password are retreived from the hdbuserstore
encrypt=True, # must be set to True when connecting to HANA Cloud
sslValidateCertificate=False # True HC, False for HANA Express.
)
#If no errors, print connected
print('connected')
c1 = conn.cursor()
c1.execute("SET SCHEMA R_C") # <-- here we set the current schema for the connection
c1.execute("SELECT current_schema FROM DUMMY") # <-- checking the current schema
rows = c1.fetchall(); # <-- [('R_C',)]
This works well for me and I don't see any side-effects besides the additional command to set the schema.
Im able to connect to Oracle Db successfully when i hardcode the Db details like " connection = cx_Oracle.connect("uname/pass#192.168.xxx.yyy:port/db")" but how to pass the variable values to connect to the db?
I tried some like this.
connection = cx_Oracle.connect("{}/{}#{}:{}/{}".format(uname,password,IP,port,db))
which is not working as expected so please share some thought on this to make it work.
def knowcobrand(request):
value_type = request.POST.get('CobranSelection')
cobrand_value = request.POST.get('cobrand')
env = request.POST.get('NewEnvName')
print(value_type)
print(cobrand_value)
print(env)
# feed = Environments.objects.get(Q(Env_name__icontains=env))
# print(feed.user_name)
connection = cx_Oracle.connect("app/app#192.168.xxx.yy:port/db")
I want to use the variable's value of value_type and env for Db connection
EDIT: You should probably run through the Django tutorial, it will explain the basics of Django and using the ORM
You should configure your database connection in your settings
There is a specific example for oracle
You can now use the Django ORM (after running migrations)
If you want a raw cursor for the database you can still use Django for this like so
from django.db import connection
with connection.cursor() as c:
c.execute(...)
I am making a database manager in Python and I want the user to be able to select a database.
I know that one can connect to a database using the following code
connection = pymysql.connect(
host='localhost'
user='root'
passwd=''
db='my_database'
)
But what if the user wants to connect to a different database later on? How would I tell connection to connect to a different database? Or better yet, omit db and then add it later on.
Calling pymysql.connect actually creates the connection to the database. If you want to connect to a different database you should create a new connection object, rather than trying to reuse the same one. You could assign it to the same variable name if you wanted to 'reuse' it later in your code.
Like this:
connection1 = pymysql.connect(
host='localhost'
user='root'
passwd=''
db='my_database'
)
connection2 = pymysql.connect(
host=?
user=?
passwd=?
db='my_other_database'
)
You can just do:
connection.close()
And then open another connection.