sqlalchemy cx_oracle cannot get results - python

sqlalchemy+cx_Oracle may not be in your domain.
However, if you can help me giving few web links/helps will be nice.
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table
import cx_Oracle
engine = create_engine('oracle+cx_oracle://user:passwd#FTSDBLAB')
meta = MetaData()
meta.reflect(bind=engine)
tbl_mgr_theater = Table('mgr_table', meta, autoload=True, autoload_with=engine)
connection = engine.connect()
result = connection.execute(tbl_mgr_theater.select())
print(result.rowcount())
gives the following ERROR:
Traceback (most recent call last):
File "", line 1, in
TypeError: 'int' object is not callable
Error closing cursor
Traceback (most recent call last):
AttributeError: 'cx_Oracle.Cursor' object has no attribute 'lastrowid'

First of all, rowcount is an attribute, so you sould use in this way:
print(result.rowcount)
But it will return 0. Why?
Because is only useful in an UPDATE or DELETE statement. Contrary to what the Python DBAPI says, it does not return the number of rows available from the results of a SELECT statement as DBAPIs cannot support this functionality when rows are unbuffered.
How can I get the rowcount of a SELECT statement?
You can SELECT with COUNT in this way:
result = connection.execute(tbl_mgr_theater.select().count())
It will return a ResultProxy. But if you want an int result, you could do:
result=[x for x in connection.execute(tbl_mgr_theater.select().count())][0][0]
As you know is a SELECT COUNT statement (it will only return one field), you could set the first [0], the second is to parse the RowProxy to int.
Hope it helps you.

Related

how to insert a numpy array having only one element to mysql db?

i am having a python program which has got a numpy array with a single element say a=['this is the element']
i need to insert this value to my database(MySQL).
i used execute() but it is showing an attribute error
my sql part to select data from table is this :
import pandas as pd
import mysql.connector
mysql_cn=mysql.connector.connect(user='root', password='',
host='127.0.0.1',port='3388',
database='proj')
X = pd.read_sql('select stamp from test;', con=mysql_cn)
mysql_cn.close()
so what has to be done since mysql_cn.execute() is not working?
i also tried pd.to_sql but it is also not working
this is the error for execute()
Traceback (most recent call last):
File "C:\Python34\data\test.py", line 132, in <module>
haa=mysql_cn.execute('select stamp from test;')// this is my simple query not my actual query
AttributeError: 'MySQLConnection' object has no attribute 'execute'
You need a cursor. You have to create a cursor from your mysql_cn then you can call execute on the cursor.
cursor = mysql_cn.cursor()
# Now call cursor.execute ....

Flask sqlalchemy: error when query using sqlachemy core

Due to I have create many APIs in MySQLdb module, and now I need to shift to sqlalchemy, I wish to use the sqlalchemy core so that not many changes needed. I am using MySQL now.
When I change to db.session.execute that previously work for Mysqldb using cur.execute(), error occurred.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Stock' is not defined
Below is the code with sqlalchemy
db = SQLAlchemy(app)
#app.route('/KJ/<Stock>', methods=['GET'])
def KJstock(Stock):
try:
call = db.session.execute("SELECT * FROM KJ WHERE Stock LIKE %s",(Stock,))
col = ['index','Stock','Name','MACD','STOCH','RSI','ATR','Bollinger','SMA','SMAcross',]
c = call.fetchall()
d = [OrderedDict(zip(col,t)) for t in c]
except Exception:
return 'Error: unable to fetch items'
return jsonify({'Stock': d})

Syntax Error near "CHANGE" in sqlite3

I am attempting to execute the following (move a column to be the first one)
import sqlite3
db = sqlite3.connect('adatabase.sqlite')
c = db.cursor()
c.execute('ALTER TABLE tab1 CHANGE COLUMN r r def FIRST')
Unfortunately I get this error
Traceback (most recent call last):
File "<input>", line 1, in <module>
OperationalError: near "CHANGE": syntax error
What could be? Thanks in advance
SQLite does not support a CHANGE COLUMN feature; if any.
Only the RENAME TABLE and ADD COLUMN variants of the ALTER TABLE
command are supported
See all missing features: SQL Features That SQLite Does Not Implement

I'm trying to use sql command on Python 3.51 and dbf 0.96.005 (for VFP). it have error

import dbf
table = dbf.Table('C:/test/MAS.DBF')
table.open()
records = table.sql("select * where SUPCOD = 1.YATHAI")
which gives:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
records = table.sql("select * where SUPCOD = 1.YATHAI")
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\site-packages\dbf\ver_33.py", line 4637, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'VfpTable' object has no attribute '(supcod = column, 1.YATHAI = value in condition )
I need to make the program read data from vfp and insert into PostgreSQL.
For some examples of dbf and sql (called pql in the dbf module as it is not full sql syntax) check out this answer.
I suspect your immediate problem will by fixed by adding quotes around the value you want to match and doubling the equal sign (it's really Python syntax):
records = table.sql("select * where SUPCOD == '1.YATHAI'")

How to use SQLAlchemy reflection with Sybase? [answer: turns out it's not supported!]

I'm trying to learn more about the .egg concept and overriding methods in Python. Here's the error message I'm receiving:
Traceback (most recent call last):
File "C:/local/work/scripts/plmr/plmr_db.py", line 42, in <module>
insp.reflecttable(reo_daily_table, column_list)
File "build\bdist.win32\egg\sqlalchemy\engine\reflection.py", line 370, in reflecttable
File "build\bdist.win32\egg\sqlalchemy\engine\reflection.py", line 223, in get_columns
File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 260, in get_columns
NotImplementedError
Here's the specific function from base.py:
def get_columns(self, connection, table_name, schema=None, **kw):
"""Return information about columns in `table_name`.
Given a :class:`.Connection`, a string
`table_name`, and an optional string `schema`, return column
information as a list of dictionaries with these keys:
name
the column's name
type
[sqlalchemy.types#TypeEngine]
nullable
boolean
default
the column's default value
autoincrement
boolean
sequence
a dictionary of the form
{'name' : str, 'start' :int, 'increment': int}
Additional column attributes may be present.
"""
raise NotImplementedError()
So my question is - do I override this function by writing a new method in my main module? Or am I missing a step somewhere along the way with my imports? Or am I just completely off track here?
Any and all help is appreciated :)
edit: adding my code
import sys
from sqlalchemy import create_engine, select, Table, MetaData
from sqlalchemy.engine import reflection
dbPath = 'connection_string'
engine = create_engine(dbPath, echo=True)
connection = engine.connect()
#reflect tables into memory
meta = MetaData()
reo_daily_table = Table('reo_daily',meta)
insp = reflection.Inspector.from_engine(engine)
column_list=[...]
insp.reflecttable(reo_daily_table, column_list)
connection.close()
EDIT:
The Sybase dialect currently lacks the ability to reflect tables.
You have misunderstood completely. You do not need to subclass anything and this problem has nothing to do with eggs and .ini files at all.
You are not supposed to instantiate Inspector this way. If you read
SQLAlchemy docs carefully, you will notice that you are not supposed to use Reflection constructor directly; instead you should write
insp = reflection.Inspector.from_engine(engine)

Categories