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})
Related
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.
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
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'")
I'm trying to use SQLite with python and I'm going over examples from the python website. One example is to build a shell for SQLite:
py
This is the beginning of the script
import sqlite3
con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()
I'm loading the file from a text editor, and I'm confused by the error that I get when I import the file.
>>>import SQLoad
Traceback (most recent call last):
File"<stdin>", line 1, in <module>
File "SQLoad.py", line 1, in <module>
c = conn.cursor()
NameError: name 'conn' is not defined
I'm confused because 'conn' isn't being defined in what I'm uploading. Is it something that has to be defined?
Your first code block shows that the connection variable is named con.
The error message shows that you have written that variable as conn, and that this is in the first line of SQLoad.py, where the connection cannot have been opened yet.
Your first code block looks correct, but it is not what is actually stored in SQLoad.py.
I have a very weird problem with mysqldb (mysql module for python).
I have a file with queries for inserting records in tables. If I call the functions from the file, it works just fine; but when trying to call one of the functions from another file it throws me a
_mysql_exception.InterfaceError: (0, '')
I really don't get what I'm doing wrong here..
I call the function from buildDB.py :
import create
create.newFormat("HD", 0,0,0)
The function newFormat(..) is in create.py (imported) :
from Database import Database
db = Database()
def newFormat(name, width=0, height=0, fps=0):
format_query = "INSERT INTO Format (form_name, form_width, form_height, form_fps) VALUES ('"+name+"',"+str(width)+","+str(height)+","+str(fps)+");"
db.execute(format_query)
And the class Database is the following :
import MySQLdb
from MySQLdb.constants import FIELD_TYPE
class Database():
def __init__(self):
server = "localhost"
login = "seq"
password = "seqmanager"
database = "Sequence"
my_conv = { FIELD_TYPE.LONG: int }
self.conn = MySQLdb.connection(host=server, user=login, passwd=password, db=database, conv=my_conv)
# self.cursor = self.conn.cursor()
def close(self):
self.conn.close()
def execute(self, query):
self.conn.query(query)
(I put only relevant code)
Traceback :
Z:\sequenceManager\mysql>python buildDB.py
D:\ProgramFiles\Python26\lib\site-packages\MySQLdb\__init__.py:34: DeprecationWa
rning: the sets module is deprecated
from sets import ImmutableSet
INSERT INTO Format (form_name, form_width, form_height, form_fps) VALUES ('HD',0
,0,0);
Traceback (most recent call last):
File "buildDB.py", line 182, in <module>
create.newFormat("HD")
File "Z:\sequenceManager\mysql\create.py", line 52, in newFormat
db.execute(format_query)
File "Z:\sequenceManager\mysql\Database.py", line 19, in execute
self.conn.query(query)
_mysql_exceptions.InterfaceError: (0, '')
The warning has never been a problem before so I don't think it's related.
I got this error when I was trying to use a closed connection.
Problem resolved.. I was initializing the database twice.. Sorry if you lost your time reading this !
I couldn't get your setup to work. I gives me the same error all the time. However the way you connect to and make queries to the db with the query seems to be "non-standard".
I had better luck with this setup:
conn = MySQLdb.Connection(user="user", passwd="******",
db="somedb", host="localhost")
cur = conn.cursor()
cur.execute("insert into Format values (%s,%s,%s,%s);", ("hd",0,0,0))
This way you can take advantage of the db modules input escaping which is a must to mitigate sql injection attacks.