there are two methods to connect mysql using python,
1
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',host='127.0.0.1',database='employees')
cnx.close()
2
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="john", # your username
passwd="megajonhy", # your password
db="jonhydb") # name of the data base
cur = db.cursor()
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
I do not know the differences between MySQLdb and mysql connector,when should I use MySQLdb and when should I use mysql connector? Please tell me ,thanks very much.
MySQLdb is a C module that links against the MySQL protocol implementation in the libmysqlclient library. It is faster, but requires the library in order to work.
mysql-connector is a Python module that reimplements the MySQL protocol in Python. It is slower, but does not require the C library and so is more portable.
Related
Need to use cx_oracle module with python 3.x version to connect Oracle 19c with TLS. There are firewalls and proxies.
How to implement it?
Do I have to use Oracle Wallets?
Is TLS 1.2 good enough or I need TLS 1.3 in 2022?
import cx_Oracle
conn = cx_Oracle.connect("uname/pwd#//localhost:1521/sd")
cur = conn.cursor()
cur.execute("SELECT 'Hello' FROM dual")
res = cur.fetchall()
If this is a cloud DB you no longer always need a wallet. With recent Oracle Client libraries you can use 1-way TLS. See Easy wallet-less connections to Oracle Autonomous Databases in Python.
I am trying to connect to Azure MySQL Database Service. I am using
pyodbc==3.0.3
python 2.7
My Connection string looks like this
connection_string = "DRIVER={MySQL};SERVER={server_name}.mysql.database.azure.com;PORT=3306;DATABASE" \
"={my_database_name};UID={username#server_name};PWD={password};CHARSET=UTF8;" \
"sslca=/home/sachin/BaltimoreCyberTrustRoot.crt.pem;sslverify=1"
cnxn = pyodbc.connect(connection_string)
But the same configuration works with mymysql.connector is working fine.
import mysql.connector
cnx = mysql.connector.connect(user="{username#servername}", password="{password}",
host="{server_name}.mysql.database.azure.com",
port=3306, database="{database_name}", ssl_ca="/home/sachin//root.crt",
ssl_verify_cert=True)
cnx.cursor()
I can not use mysql.connector for now. So need some suggestion if any one have faced this issue.
I had the same problem and fixed it by setting sslverify=1 to sslverify=0.
e.g. for Azure:
;sslca={BaltimoreCyberTrustRoot.crt.pem}; sslverify=0; Option=3;'
sqlplus sys/Oracle_1#pdborcl as sysdba;
i'm using this command to connect to Oracle 12c from Command Prompt.
How can i connect to the db using cx_Oracle. I'm new to Oracle DB.
I think this is the equivalent of the sqlplus command line that you posted:
import cx_Oracle
connect_string = "sys/Oracle_1#pdborcl"
con = cx_Oracle.connect(connect_string,mode=cx_Oracle.SYSDBA)
I tried it with a non-container database and not with a pdb so I can't verify that it would work with a pdb. You may not want to connect as sys as sysdba unless you know that you need that level of security.
Bobby
You can find the documentation here cx_Oracle docs
To query the database, use the below algorithm
import cx_Oracle
dsn = cx_Oracle.makedsn(host, port, sid)
connection = cx_Oracle.connect(dsn,mode = cx_Oracle.SYSDBA)
query = "SELECT * FROM MYTABLE"
cursor = connection.cursor()
cursor.execute(query)
resultSet=cursor.fetchall()
connection.close()
The above code works to fetch data from MYTABLE connecting to the above dsn.
Better to go through cx_Oracle docs.
I'm guessing this is a pretty basic question, but I can't figure out why:
import psycopg2
psycopg2.connect("postgresql://postgres:postgres#localhost/postgres")
Is giving the following error:
psycopg2.OperationalError: missing "=" after
"postgresql://postgres:postgres#localhost/postgres" in connection info string
Any idea? According to the docs about connection strings I believe it should work, however it only does like this:
psycopg2.connect("host=localhost user=postgres password=postgres dbname=postgres")
I'm using the latest psycopg2 version on Python2.7.3 on Ubuntu12.04
I would use the urlparse module to parse the url and then use the result in the connection method. This way it's possible to overcome the psycop2 problem.
from urlparse import urlparse # for python 3+ use: from urllib.parse import urlparse
result = urlparse("postgresql://postgres:postgres#localhost/postgres")
username = result.username
password = result.password
database = result.path[1:]
hostname = result.hostname
port = result.port
connection = psycopg2.connect(
database = database,
user = username,
password = password,
host = hostname,
port = port
)
The connection string passed to psycopg2.connect is not parsed by psycopg2: it is passed verbatim to libpq. Support for connection URIs was added in PostgreSQL 9.2.
To update on this, Psycopg3 does actually include a way to parse a database connection URI.
Example:
import psycopg # must be psycopg 3
pg_uri = "postgres://jeff:hunter2#example.com/db"
conn_dict = psycopg.conninfo.conninfo_to_dict(pg_uri)
with psycopg.connect(**conn_dict) as conn:
...
Another option is using SQLAlchemy for this. It's not just ORM, it consists of two distinct components Core and ORM, and it can be used completely without using ORM layer.
SQLAlchemy provides such functionality out of the box by create_engine function. Moreover, via URI you can specify DBAPI driver or many various postgresql settings.
Some examples:
# default
engine = create_engine("postgresql://user:pass#localhost/mydatabase")
# psycopg2
engine = create_engine("postgresql+psycopg2://user:pass#localhost/mydatabase")
# pg8000
engine = create_engine("postgresql+pg8000://user:pass#localhost/mydatabase")
# psycopg3 (available only in SQLAlchemy 2.0, which is currently in beta)
engine = create_engine("postgresql+psycopg://user:pass#localhost/test")
And here is a fully working example:
import sqlalchemy as sa
# set connection URI here ↓
engine = sa.create_engine("postgresql://user:password#db_host/db_name")
ddl_script = sa.DDL("""
CREATE TABLE IF NOT EXISTS demo_table (
id serial PRIMARY KEY,
data TEXT NOT NULL
);
""")
with engine.begin() as conn:
# do DDL and insert data in a transaction
conn.execute(ddl_script)
conn.exec_driver_sql("INSERT INTO demo_table (data) VALUES (%s)",
[("test1",), ("test2",)])
conn.execute(sa.text("INSERT INTO demo_table (data) VALUES (:data)"),
[{"data": "test3"}, {"data": "test4"}])
with engine.connect() as conn:
cur = conn.exec_driver_sql("SELECT * FROM demo_table LIMIT 2")
for name in cur.fetchall():
print(name)
# you also can obtain raw DBAPI connection
rconn = engine.raw_connection()
SQLAlchemy provides many other benefits:
You can easily switch DBAPI implementations just by changing URI (psycopg2, psycopg2cffi, etc), or maybe even databases.
It implements connection pooling out of the box (both psycopg2 and psycopg3 has connection pooling, but API is different)
asyncio support via create_async_engine (psycopg3 also supports asyncio).
This question already has answers here:
What do I need to read Microsoft Access databases using Python?
(12 answers)
Closed 9 years ago.
Is there a library for using MS Access database in python? The win32 module is not as easy as the MySQL library. Is there a simpler way to use MS Access with Python?
Depending on what you want to do, pyodbc might be what you are looking for.
import pyodbc
def mdb_connect(db_file, user='admin', password = '', old_driver=False):
driver_ver = '*.mdb'
if not old_driver:
driver_ver += ', *.accdb'
odbc_conn_str = ('DRIVER={Microsoft Access Driver (%s)}'
';DBQ=%s;UID=%s;PWD=%s' %
(driver_ver, db_file, user, password))
return pyodbc.connect(odbc_conn_str)
conn = mdb_connect(r'''C:\x.mdb''') # only absolute paths!
Note: you may download the freely-redistributable new-driver, if you don't have MSOffice installed.
I don't think win32 is hard. Try use its odbc module. Example of code working with ODBC and PostgreSQL database:
import odbc
def get_pg_ver(db_alias):
connection = odbc.odbc(db_alias)
try:
cursor = connection.cursor()
cursor.execute('SELECT version()')
for row in cursor.fetchall():
print row[0]
finally:
connection.close()
get_pg_ver('odbc_name/user/passwd')
This is very similar for every db driver I used in Python and Jython (I work with PostgreSQL, Oracle and Informix).
You can use pypyodbc to easily create an empty Access MDB file on win32 platform, and also compact existing Access MDB files.
It can be as easy as:
import pypyodbc
pypyodbc.win_create_mdb( "D:\\Your_MDB_file_path.mdb" )
More over, as an dbi 2.0 ODBC library, pypyodbc is highly compatible with pyodbc, you can do SQL database queries like SELECT, INSERT, UPDATE with the library.
Here is the full Tutorial about pypyodbc's Access support.
Disclaimer: I'm the developer of pypyodbc.
I had some recent success using pywin32's adodbapi module.
The following snippet was taken from this website:
import adodbapi
database = "db1.mdb"
constr = 'Provider=Microsoft.Jet.OLEDB.4.0; Data Source=%s' % database
tablename = "address"
# connect to the database
conn = adodbapi.connect(constr)
# create a cursor
cur = conn.cursor()
# extract all the data
sql = "select * from %s" % tablename
cur.execute(sql)
# show the result
result = cur.fetchall()
for item in result:
print item
# close the cursor and connection
cur.close()
conn.close()