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.
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)
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]
I have to connect to an Oracle server and only use a specific database on the server. I have logon information like this:
hostname = 'xxxxx.yyyy.xxxx.net:1521/{server_name}'
user_name= 'user'
password = 'password'
db_name= 'uuuu'
cx_Oracle.connect(user_name, password, hostname)
How can specify the db_name in the connect statement in the connect statement?
The above allows me to query: select * from uuuu.my_table;. So how can I specify uuuu in the connect such that I don't have to add each time.
"uuuu" in your example appears to be a schema name not a database name. You cannot specify a schema name in your connection string (other than by logging in as the "uuuu" user). Once you have connected to the database, however, you can run the statement
alter session set current_schema = uuuu;
That will cause the statement
select * from my_table
to look for a my_table object in the "uuuu" schema rather than looking for it in the current user's schema. Alternatively, you can create synonyms (public or private) for my_table and the other "uuuu" schema objects you want to reference.
From the docs...
import cx_Oracle
userpwd = ". . ." # Obtain password string from a user prompt or environment variable
connection = cx_Oracle.connect("hr", userpwd, "dbhost.example.com/orclpdb1", encoding="UTF-8")
The 'ocrlpdb1' at the end of the connect string, that's the Service name for the database, that is running on dbhost.example.com. We're assuming Oracle Listener on that machine is using port 1521 (the default).
I am trying to connect to a remote Oracle database using Python.
I am able to access the database directly using DBeaver and I have copied the parameters in the Python code below from the "Connection Configuration --> Connection settings --> General" tab (which can be opened by right-clicking on the database and selecting "Edit connection"):
import cx_Oracle
host_name = # content of "Host"
port_number = # content of "Port"
user_name = # content of "User name"
pwd = # content of "Password"
service_name = # content of "Database" (the "Service Name" option is selected)
dsn_tns = cx_Oracle.makedsn(host_name, port_number, service_name = service_name)
conn = cx_Oracle.connect(user = user_name, password = pwd, dsn = dsn_tns)
However, I get the following error:
DatabaseError: ORA-12541: TNS:no listener
Other answers I found related to this question suggested modifying some values inside the listener.ora file, but I have no such file on my computer nor do I know where it can be retrieved. Does anyone have any suggestions?
There would be two reason for that error.
The database was briefly unavailable at the time when you tried to access
The Oracle client application on your machine is not configured correctly
I think thi config is not correct.
See the link : https://oracle.github.io/python-cx_Oracle/
ip = '192.168.1.1'
port = 1521
SID = 'YOURSIDHERE'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect('username', 'password', dsn_tns)
I am looking to establish a connection to MS SQL through a DSN using pyodbc. what I am seeing is that I cannot connect to database unless I specify the username (PID) and password (PWD) in the connection string like this:
conn_str = 'DSN=MYMSSQL;UID=sa;PWD=password'
so if I use PID and PWD it works but if I put the PID and PWD in my DSN configuration (MYMSSQL) and remove these two attributes from conn_str then it doesn't work, below is the DSN configuration:
[MYMSSQL]
Description = Test to SQLServer
Driver = FreeTDS
Servername = MYMSSQL
UID = sa
PWD = password
Database = tempdb
Observation from the pyodbc API docs, apprently no way to do it without UID and PWD
def connect(p_str, autocommit=False, ansi=False, timeout=0, **kwargs): # real signature unknown; restored from __doc__
"""
connect(str, autocommit=False, ansi=False, timeout=0, **kwargs) --> Connection
Accepts an ODBC connection string and returns a new Connection object.
**The connection string will be passed to SQLDriverConnect, so a DSN connection
can be created using:**
**cnxn = pyodbc.connect('DSN=DataSourceName;UID=user;PWD=password')**
To connect without requiring a DSN, specify the driver and connection
information:
DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=user;PWD=password
Note the use of braces when a value contains spaces. Refer to SQLDriverConnect
documentation or the documentation of your ODBC driver for details.
The connection string can be passed as the string `str`, as a list of keywords,
or a combination of the two. Any keywords except autocommit, ansi, and timeout
(see below) are simply added to the connection string.
connect('server=localhost;user=me')
connect(server='localhost', user='me')
connect('server=localhost', user='me')
The DB API recommends the keywords 'user', 'password', and 'host', but these
are not valid ODBC keywords, so these will be converted to 'uid', 'pwd', and
'server'.
pass
The ODBC driver managers that I've dealt with (Windows' built-in DM, and unixODBC on Linux) silently ignore UID= and PWD= entries in "System DSN" and "User DSN" definitions. They do respect those entries in "File DSN" definitions, so you could create a file named "mymssql.dsn" in a secure location containing
[ODBC]
Description = Test to SQLServer
Driver = FreeTDS
Servername = MYMSSQL
UID = sa
PWD = password
Database = tempdb
and then use
conn_str = 'FILEDSN=/path/to/mymssql.dsn'