how to run a .sql file on different database in python - python

So this is my requirement. I've some use python module to execute .sql files on different databases such as oracle, MSSQL, db2, etc. on different platforms such linux and windows. In my requirement i can't open the sql file and run each command. I've to run .sql file as whole. I was reading about sql alchemy but it seems as it has to execute each statement. So is there is any module to run the complete .sql file
PS: - I've .sql file with respect to each database, i.e. if I've abc.sql for oracle then every statement is compatible to run on oracle database and if this abc.sql file is not supposed to run on MSSQL or DB2, my program will not execute it on these database.

No. There is standard SQL language, but this standard says only how SELECT, INSERT etc should work. There is nothing about .sql files. This way each DBMS vendor has his own ways of working with such files. In PostgreSQL you can easily run psql command line programm with your file as input. In Oracle world you can try to do the same using sqlplus but of course such .sql files will vary. In PostgreSQL you should set encoding of input file using non-standard SQL command that other vendors will report as error. For such things Oracle uses environment settings. With Oracle your .sql file for sqlplus must end with COMMIT; EXIT; etc. Even datetime string literals are different for each vendor. MS SQL uses {ts '...'} which will not work with Informix, PostgreSQL nor Oracle.
Shortly: it seems impossible to do such program for each database.
All you can do is to invite additional layer that will change your standard input file (add some header and footer, convert datetime literals etc). Then such prepared file can be run against command line tools given by database vendor, or by your specialized program able to execute such converted file.
EDIT:
It seems that you have different files for different databases, and even for different database versions. You can also use native programs that are able to run .sql file. So the only problem is to detect database and database version and execute proper file using proper native client. This is code in Jython (I often use JDBC, but you can use DB-API and Python db drivers):
def get_db_version(db):
dbname = ''
ver = ''
c = db.createStatement()
try:
rs = c.executeQuery("SELECT FIRST 1 DBINFO('version','full') FROM systables")
dbname = 'informix'
# IBM Informix Dynamic Server Version 11.50.FC4
except:
try:
rs = c.executeQuery("SELECT * FROM v$version WHERE banner LIKE 'Oracle%'")
dbname = 'oracle'
# Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
except:
try:
rs = c.executeQuery("SELECT version()")
dbname = 'postgresql'
# PostgreSQL 9.2.4 on ..., 64-bit
# PostgreSQL 9.3.0 on ..., 64-bit
except:
raise
if dbname:
while (rs.next()):
ver = rs.getString(1)
return dbname, ver
def select_sql_app_and_file():
import_app = None
ver_postfix = ''
dbname, ver = get_db_version(create_db_connection())
if dbname == 'postgresql':
import_app = 'psql'
if 'PostgreSQL 9.2' in ver:
import_app = 'psql92'
ver_postfix = '92'
elif dbname == 'oracle':
import_app = 'sqlplus'
if 'Release 11.' in ver:
import_app = 'sqlplus11'
ver_postfix = '11'
# ...
sql_file_name = 'import_' + dbname + ver_postfix + '.sql'
return import_app, sql_file_name
def run_sql_file():
import_app, sql_file_name = select_sql_app_and_file()
if import_app:
execute_import_app(import_app, sql_file_name)

Related

Export data from Oracle Database 12c using Python 2.7

I'm trying to export a table, contained within an Oracle 12c database, to csv format - using Python 2.7. The code I have written is shown below:
import os
import cx_Oracle
import csv
SQL = 'SELECT * FROM ORACLE_TABLE'
filename = 'C:\Temp\Python\Output.csv'
file = open(filename, 'w')
output = csv.writer(file, dialect='excel')
connection = cx_Oracle.connect('username/password#connection_name')
cursor = connection.cursor()
cursor.execute(SQL)
for i in cursor:
output.writerow(i)
cursor.close()
connection.close()
file.close()
This code yields an error in the line where I define 'connection':
ORA-12557: TNS:protocol adapter not loadable
How can I remedy this? Any help would be appreciated.
Please note: I have already encountered StackOverflow responses to very similar problems to this. However, they often suggest changing the path within environment variables - I cannot do this since I don't have appropriate administer privileges. Thanks again for your assistance.
ORA-12557 is caused by problems with the %ORACLE_HOME% on Windows. That's the usual suggestion is to change the PATH setting.
"I cannot do this since I don't have appropriate administer privileges."
In which case you don't have too many options. Perhaps you could navigate to the ORACLE_HOME directory and run your script from there. Otherwise look to see what other tools you have available: Oracle SQL Developer? TOAD? SQL*Plus?
We found that by navigating to config -> Oracle and editing the file 'tnsnames.ora' the problem can be solved. The tnsnames file appears as follows:
connection_name =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS= ... )
)
(CONNECT_DATA =
(SERVICE_NAME= ...)
)
)
By changing the first instance of connection_name to connection_name.WORLD, then typing
set ORACLE_HOME=
into the command line before executing the Python script, the above script now runs with no error.
I use ini-file to store DB connection parameters. Hope it helps.
self.mydsn = cx_Oracle.makedsn(self.parser.get('oracle', 'db'),self.parser.get('oracle', 'port'),self.parser.get('oracle', 'service_name'))
try:
self.connpool = cx_Oracle.SessionPool(user=self.parser.get('oracle', 'username'),password=self.parser.get('oracle', 'userpass'),dsn=self.mydsn,min=1,max=5,increment=1)
except Exception as e:
print e
You can use this python script for oracle csv export:
https://github.com/teopost/csv_exp

MS Analysis Services OLAP API - Execute MDX query [duplicate]

I was able to connect to SQL server Analysis service in Python using Microsoft.AnalysisServices.dll, and now I can't execute query on cube.
I've tried Execute method same as following:
amoServer.Execute('select from finance')
After issuing Execute method I have this error:
<Microsoft.AnalysisServices.XmlaError object at 0x000000000000002B [Microsoft.AnalysisServices.XmlaError]>
Note: I'm using IronPython with Python 2.7 on Windows Server 64Bit.
What's the problem?
its better use Microsoft.AnalysisServices.AdomdClient.dll and mdx query.
and set query result in Datasets in Ststem.Data assembly
something like this:
clr.AddReference ("Microsoft.AnalysisServices.AdomdClient.dll")
clr.AddReference ("System.Data")
from Microsoft.AnalysisServices.AdomdClient import AdomdConnection , AdomdDataAdapter
from System.Data import DataSet
conn = AdomdConnection("Data Source=0.0.0.0;Catalog=MyCatalog;")
conn.Open()
cmd = conn.CreateCommand()
cmd.CommandText = "your mdx query" # in your case 'select from finance'
adp = AdomdDataAdapter(cmd)
datasetParam = DataSet()
adp.Fill(datasetParam)
conn.Close();
# datasetParam hold your result as collection a\of tables
# each tables has rows
# and each row has columns
print datasetParam.Tables[0].Rows[0][0]

What is the counterpart of piping a schema into sqlite in Linux to Windows (Flask)

I am following the tutorial on the Flask's website
To give you some context, I am working in a directory flaskapp that has the flaskr.py file and schema.sql. The virtualenv is activated.
schema.sql is
drop table if exists entries;
create table entries (
id integer primary key autoincrement,
title text not null,
text text not null
);
flaskr.py with unneccesary part trimmed:
DATABASE = '/tmp/flaskr.db'
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
The concerned part in the tutorial says-
Flaskr is a database powered application as outlined earlier, and more precisely, an application powered by a relational database system. Such systems need a schema that tells them how to store that information. So before starting the server for the first time it’s important to create that schema.
Such a schema can be created by piping the schema.sql file into the sqlite3 command as follows:
sqlite3 /tmp/flaskr.db < schema.sql
I am pretty sure that I have located the problem, because on running it, the error is:
File "C:\Users\Hp1\Desktop\flaskr\flaskrapp\flaskr.py", line 19,
in connect_db
return sqlite3.connect(app.config['DATABASE'])
sqlite3.OperationalError: unable to open database file
The 'DATABASE' in my flaskr.py file is '/tmp/flaskr.db'. So I made a blank flaskrdb.db file in my working directory and replaced the 'tmp/flaskr.db' in the flaskr.py DATABASE value. But I am unable to use the piping operation, because it is given for Linux. How do I do that in Windows?
I am unable to find sqlite3.exe anywhere on my pc.
A quick way would be to use your existing Python installation and do it by hand, just for the purpose of your tutorial.
>>> import sqlite3
>>> conn = sqlite3.connect("flaskr.db") # Replace this with the path to the flaskr.db in your working directory
>>> c = conn.cursor()
>>> c.execute("drop table if exists entries;")
<sqlite3.Cursor object at 0x0000000002C3BB90>
>>> c.execute("""create table entries (
... id integer primary key autoincrement,
... title text not null,
... text text not null
... );""")
<sqlite3.Cursor object at 0x0000000002C3BB90>
>>>
If you're going to need to interact with sqlite3 databases more, consider installing and learning the tools from the SQLite website: https://www.sqlite.org/download.html -- You'll want sqlite-tools-win32-x86-3110100.zip.
There is a commandline sqlite application distributed with those tools which will work with the piping example from the tutorial.

creating database in python

I have installed mysql for python and running python from command line. I am getting syntax error while creating a database.
>>> import MySQLdb
>>> CREATE DATABASE chom;
File "<stdin>", line 1
CREATE DATABASE chom;
^
SyntaxError: invalid syntax
CREATE DATABASE chom; this should be run from the MySQL command line client, not from the Python shell.
So, first type mysql -u yourusername -p from your command line. It will ask you for a password, type it in. Then you will get a prompt like this mysql>. Here is where you would type that query.
Now, if you want to do this through Python, you can, but it will require some more work.
>>> import MySQLdb as db
>>> con = db.connect(user="foo", passwd="secret")
>>> cur = con.cursor()
>>> cur.execute('CREATE DATABASE chom;')
See this guide for some examples on how to work with Python and MySQL using the standard DB API.
If you want create a database,you can try:
import MySQLdb
db1 = MySQLdb.connect(host="localhost",user="root",passwd="****")
cursor = db1.cursor()
sql = 'CREATE DATABASE chom'
cursor.execute(sql)

Python Create Access database using win32com

I want to create an Access database (*.accdb) from within a Python script.
Using win32com and Dispatch I can call the application. However, I cant find anything on how to create a new database.
access = win32com.client.Dispatch('Access.Application')
At that point I have no need to put data into the database and I would do this using pyodbc - I simply need to create an empty database.
Does somebody has an example on how to do this?
Cheers Thomas
You have an Access application object. Use its DBEngine.CreateDatabase method to create your db file.
This sample worked from Python 2.7 to create an MDB format database file. To create an ACCDB, use 128 (dbVersion120) for dbVersion.
import win32com.client
oAccess = win32com.client.Dispatch('Access.Application')
DbFile = r'C:\Users\hans\Documents\NewDb.mdb'
dbLangGeneral = ';LANGID=0x0409;CP=1252;COUNTRY=0'
# dbVersion40 64
dbVersion = 64
oAccess.DBEngine.CreateDatabase(DbFile, dbLangGeneral, dbVersion)
oAccess.Quit()
del oAccess
To create a new, empty .accdb file, the following Python code should do the trick:
import win32com.client
f = 'C:\\Users\\Gord\\Desktop\\pyTest.accdb'
c = win32com.client.Dispatch('ADOX.Catalog')
c.Create('Provider=Microsoft.ACE.OLEDB.12.0;Data Source=' + f + ';')
c = None
print '"' + f + '" created.'
[Edit 1]
A comment to a blog posting here suggests that if the .Create call generates a "Class not registered" error you may need to use regsvr32.exe to re-register msadox.dll. Be aware of "bitness" when you attempt this: There are 32-bit and 64-bit versions of both of those files:
64-bit
C:\Windows\System32\regsvr32.exe
C:\Program Files\Common Files\System\ado\msadox.dll
32-bit
C:\Windows\SysWOW64\regsvr32.exe
C:\Program Files (x86)\Common Files\System\ado\msadox.dll
Also, be aware that you could be running 32-bit Python on a 64-bit machine.
[Edit 2]
I've done a few tests and have reached the conclusion that this approach did not work in this particular case because the Python script was running as 64-bit, but the 64-bit Access Database Engine was not installed. (32-bit Office only installs the 32-bit version of ACE.)
The error message was perhaps a bit misleading. It wasn't the ADOX component that was missing (not registered), it was the 64-bit version of the ACE engine itself that couldn't be found.
Furthermore, on a 64-bit machine with 32-bit Access installed, the 64-bit version of ACE will never be available because it cannot be installed
This could very well have implications when you try to manipulate data within the .accdb file from a 64-bit Python script. I didn't have Python available on my "32-bit Office on 64-bit Windows" test machine, but when I tried the following VBScript...
Option Explicit
Dim con, rst
Set con = CreateObject("ADODB.Connection")
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\Users\Gord\Desktop\adoTest.accdb;"
Set rst = CreateObject("ADODB.Recordset")
rst.Open "SELECT Field1 FROM Table1", con
Wscript.Echo rst(0).Value
rst.Close
Set rst = Nothing
con.Close
Set con = Nothing
...the results were as follows:
C:\__tmp>C:\Windows\System32\cscript.exe /nologo dataAccessTest.vbs
C:\__tmp\dataAccessTest.vbs(4, 1) ADODB.Connection: Provider cannot be found.
It may not be properly installed.
C:\__tmp>C:\Windows\SysWOW64\cscript.exe /nologo dataAccessTest.vbs
This is Table1 data in Access.
The script failed when run as 64-bit, but it worked when run as 32-bit.
Recommendation: If your machine has 32-bit Access installed you'll probably be better off running your Python scripts as 32-bit too.
import win32com.client
ConFileName = r'c:\mydb\myaccess.mdb'
try:
Catalog = win32com.client.Dispatch('ADOX.Catalog')
Catalog.Create('Provider=Microsoft.ACE.OLEDB.12.0;Data Source=' + ConFileName + ';')
Catalog = None
except:
Exception as e:
print("Database generation failed, Error="+str(e))
print("NewAccessDB.mdb created successfully")
Then you can connect to access database :
ConFileName=(r'c:\mydb\myaccess.mdb')
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + ConFileName + ';')
cursor = conn.cursor()
To insert in to the access table :
ConFileName=(r'c:\mydb\myaccess.mdb')
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' +ConFileName+ ';')
cursor = conn.cursor()
for ta in TableArray:
Sql_insert_query = "INSERT INTO Table1(ID, Value1,Value2,Value3,Value4,Value5,Value6) " \
"VALUES ('{a}','{b}','{c}','{d}','{e}','{f}','{g}')".format(a=str(ta[0]),b=str(ta[1]),c=str(ta[2]),d=str(ta[3]),e=str(ta[4]),f=str(ta[5]),g=str(ta[6]))
cursor.execute(Sql_insert_query)
conn.commit()
cursor.close()
Please follow this link for more information :
https://elvand.com/python-and-ms-access/

Categories