Python 3.2 script to connect to local MySQL database - python

I am running an Ubuntu Server. I would like for it to have a Python (v3.2) CGI script that would connect, and run a query, to the local MySQL database I have set up. Currently, the only things I found don't support Python 3.2. Please do not suggest switching to an earlier version of Python, because that is not an option for me.

pymysql - Pure Python MySQL client is very good.
It works with Python 3.x, and doesn't have any dependencies.
This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol.
Example:
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for r in cur:
print(r)
cur.close()
conn.close()

sqlalchemy supports MySQL and all versions of Python 3. It's nice because you don't have to write SQL; it makes tables look like classes and records look like objects.

BlaXpirit's answer above to use pymysql works great! But one small caveat. The link to pymysql in his comment will take you to https://github.com/petehunt/PyMySQL/ which is for python 2.x. If you are using python 3, you want to download and install pymysql3 (version 3.0.5 as of 5/12/12) from http://pypi.python.org/pypi/PyMySQL3/

Related

beginner python issue: pyodbc connection

beginner python programmer here,
I'm having an issue with pyodbc. I've included two images. The first is the code itself... and here it is again in text:
def retrieve_db(self):
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=Students;Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute("SELECT * FROM tbl_student")
for row in cursor:
print(row)
The issue is that I have an .mdf that I'm trying to connect to but when I execute the program to retrieve all records it does not connect. Really not sure what the issue is. Reading other posts across the web I believe it's something to do with the connection string itself but I can't figure out how to syntax the correct param. The pyodbc connector was installed correctly as far as I'm aware.
Can anyone help? In particular does anyone know how to create and connect to an.mdf using Visual Studio and the python pyodbc? Also, when I attempt to connect to a local DB created in MySQL workbench, I get the same issue. Any suggestions?
code in editor
the .mdf using the built in sql server on Visual Studio
the error i get
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=Students;Trusted_Connection=yes;')
According to your code you're trying to use "SQL Server" driver. Is ODBC Driver for SQL Server properly installed on your system?
If not, please, download it from Microsoft website and install.
https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver15

error when connecting oracle in python using cx_Oracle

I was trying to connect oracle database using python like below.
import cx_Oracle
conn = cx_Oracle.connect('user/password#host:port/database')
I've faced an error when connecting oracle.
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help.
I've been struggling to figure it out. I used my user name, password, host, port and database('orcl') for example,
'admin/admin#10.10.10.10:1010/orcl'.
Why coudn't it connect?
Ahh, btw I'm running all the code in azure notebooks.
That error indicates that you are missing a 64-bit Oracle client installation or it hasn't been configured correctly. Take a look at the link mentioned in the error message. It will give instructions on how to perform the Oracle client installation and configuration.
[Update on behalf of Anthony: his latest cx_Oracle release doesn't need Oracle Client libraries so you won't see the DPI-1047 error if you upgrade. The driver got renamed to python-oracledb but the API still supports the Python DB API 2.0 specification. See the homepage.]
This seems a problem with version 6.X.This problem didnot appeared in 5.X.But for my case a little workaround worked.I installed in my physical machine and only thing that i need to do was a pc reboot or reopen the terminal as i have added in the path of environment variables.You can try to install in physical machine instead using azure notebooks.
This error come when your Oracle Client is not installed or LD_LIBRARY_PATH is not set where libclntsh.so is present.
if you have Oracle client installed then search for libclntsh.so and set the LD_LIBRARY_PATH as
"export LD_LIBRARY_PATH=/app/bds/parcels/ORACLE_INSTANT_CLIENT/instantclient_11_2:$LD_LIBRARY_PATH"
Here is the full program to connect Oracle using python.
First, you need to install cx_Oracle. to install it fire the below command.
pip install cx_Oracle
import cx_Oracle
def get_databse_coonection():
try:
host='hostName'
port ='portnumber'
serviceName='sid of you database'
user = 'userName'
password = 'password'
dns = cx_Oracle.makedsn(host,port,service_name=serviceName)
con = cx_Oracle.connect(user, password, dns)
cursor = con.cursor()
query ="select * from table"
cursor.execute(query)
for c in cursor:
print(c)
except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)
finally:
if cursor:
cursor.close()
if con:
con.close()
get_databse_coonection()

Python connection to Oracle database

I am writing a Python script to fetch and update some data on a remote oracle database from a Linux server. I would like to know how can I connect to remote oracle database from the server.
Do I necessarily need to have an oracle client installed on my server or any connector can be used for the same?
And also if I use cx_Oracle module in Python, is there any dependency that has to be fulfilled for making it work?
You have to Install Instance_client for cx_oracle driver to interact with remote oracle server
http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html.
Use SQLAlchemy (Object Relational Mapper) to make the connection and interact with Oracle Database.
The below code you can refer for oracle DB connection.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('oracle+cx_oracle://test_user:test_user#ORACSG')
session_factory = sessionmaker(bind=engine, autoflush=False)
session = session_factory()
res = session.execute("select * from emp");
print res.fetchall()
Yes, you definitely need to install an Oracle Client, it even says so in cx_oracle readme.txt.
Another recommendation you can find there is installing an oracle instant client, which is the minimal installation needed to communicate with Oracle, and is the simplest to use.
Other dependencies can usually be found in the readme.txt file, and should be the first place to look for these details.

Python 3.3 Mysql Connector [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MySQL-db lib for Python 3.0?
I use python3.3 and can't connect to MySQL, because I don't find module for MySQL connector.
How do I connect to MySQL with python3.3?
There is a module called Pymysql which you may like:
"""This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol."""
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for response in cur:
print(response)
cur.close()
conn.close()
As far as I know, nobody has ported the C extension module for mysql to Python 3, but there are at least two pure-Python modules that work just fine with Python 3 (and also with PyPy, etc.):
PyMySQL
MySQL Connector/Python
A quick google for python3 mysql turns up a few more (as well as various pointers to these two projects, including previous SO questions that ask exactly the same thing).

How to use IBM_DB with older versions of DB2?

I want to connect Python to DB2 version 9.1 using IBM DB2 ODBC Driver.
Following is my code to connect Python to DB2. This program is working in the later versions of IBM DB2.
import ibm_db
conn = ibm_db.connect("DSN=PDB2;DRIVER={IBM DB2 ODBC DRIVER};DATABASE=MDBASIS;PORT=1234;PROTOCOL=TCPIP;UID=username;PWD=password","","")
stmt = ibm_db.exe_immediate(conn,"create table egg (ID SMALLINT, NAME VARCHAR(30))")
stmt = ibm_db.exe_immediate(conn,"insert into egg (ID, NAME) VALUES('1','ok')")
state = ibm_db.exe_immediate("select * from egg")
result = ibm_db.fetch_both(state)
while result != False:
print 'id = %d and name = %s' %(result[0],result[1])
result = ibm_db.fetch_both(state)
stmt = ibm_db.exe_immediate(conn,"drop table egg")
My problem is, the version of my IBM DB2 is 9.1 without FixPack and I get an error message when I try to connect to IBM DB2 9.1 version.
"[IBM][CLI Driver] CLI0133E Option type out of range. SQLSTATE=HY092 SQLCODE=-99999"
And the explanation for this error written in page http://programmingzen.com/2008/02/08/essential-guide-to-the-ruby-driver-for-db2/is:
"If you get this error, it usually means that you are using a version of DB2 that is too old. Install the latest FixPack or the latest version of DB2 (currently 9.5) to resolve the problem."
But I cannot install latest FixPack or the latest version of DB2 or in any way modify existing DB2 installation.
Question
Is there any way I can connect to DB2 version 9.1 without modifying the database, possibly using something else than IBM_DB?
I think the problem is in the client ibm_db driver. Basically you can connect to any older version from all the languages. Try to get another db2 driver. If I were you I would install the db2 client which comes with several drivers which are located in sqllib.
What version of ibm_db are you using? I am able to connect to DB2 9.1 with ibm_db 1.0.4 without problems.
Also: Based on the fact that you're specifying DSN in your connection string, I assume that you already have the database cataloged on the client as PDB2. You can greatly simply your connect statement to:
conn = ibm_db.connect('PDB2','username','password')
The only time you need to use the longer form (where you specify DATABASE/PORT/HOST/UID/PWD) is if you are using a DSN-less connection (i.e. the database has not been cataloged on the local machine).
I guess your DB2 client API version is higher than the DB2 server itself, ensure you use the same version on the client machine, try to connect and maintain your database remotely using the DB2 control center, and try to connect from python with:
conn = ibm_db.connect("MDBASIS", "username", "password")
AFAIK, this would force the wrapper to use native library instead of odbc.
ibm_db (and PyDB2 are just python modules that allow you to access the DB2 API calls through python. The DB2 queries themselves are being performed by your DB2 installation... something very separate from ibm_db and PyDB2.
It sounds like your DB2 installation is the problem, not ibm_db. You can test this by running db2 from the command line and seeing if you can execute your query directly in the db2 command line interface.

Categories

Resources