How can you fix the SQL-statement in Python?
The db connection works. However, cur.execute returns none which is false.
My code
import os, pg, sys, re, psycopg2
try:
conn = psycopg2.connect("dbname='tk' host='localhost' port='5432' user='naa' password='123'")
except: print "unable to connect to db"
cur = conn.cursor()
print cur.execute("SELECT * FROM courses") # problem here
The SQL-command in Psql returns me the correct output.
I can similarly run INSERT in Psql, but not by Python's scripts.
I get no warning/error to /var/log.
Possible bugs are
cursor(), seems to be right however
the syntax of the method connect(), seems to be ok however
You have to call one of the fetch methods on cur (fetchone, fetchmany, fetchall) to actually get the results of the query.
You should probably have a read through the a tutorial for DB-API.
You have to call cur.fetchall() method (or one of other fetch*() methods) to get results from query.
Related
I am trying to setup a python script to get some data and store it into a SQLite database. However when I am running the script a .fuse_hidden file is created.
On windows no .fuse_hidden file is observed but on ubuntu it generates at each call. The .fuse_hidden file seems to contain some form of sql query with input and tables.
I can delete the files without error during runtime but they are not deleted automatically. I make sure to end my connection to the db when I am finished with the query.
lsof give no information.
I am out of ideas on what to try next to get the files removed automatically. Any suggestions?
Testing
In order to confirm that it is nothing wrong with the code I made a simple script
(Assume there is an empty error.db)
import sqlite3
conn = sqlite3.connect("error.db")
cur = conn.cursor()
create_query = """
CREATE TABLE Errors (
name TEXT
);"""
try:
cur.execute(create_query)
except:
pass
cur.execute("INSERT INTO Errors (name) VALUES(?)", ["Test2"])
conn.commit()
cur.close()
conn.close()
I wrote this code mentioned below to get a basic select statement output from mysql database using python.
The code is :
import warnings
warnings.filterwarnings(action="ignore", message='the sets module is deprecated')
import MySQLdb
import sys
try:
db =MySQLdb.connect(host='********',user='Admin',passwd='******',db='data')
except Exception as e:
sys.exit('Not working')
cursor = db.cursor()
cursor.execute('select * from user')
results = cursor.fetchall()
print results
But the output that is get is :
((1L,), (2L,))
Please assist
Thanks in advance :)
My simple test code is listed below. I created the table already and can query it using the SQLite Manager add-in on Firefox so I know the table and data exist. When I run the query in python (and using the python shell) I get the no such table error
def TroyTest(self, acctno):
conn = sqlite3.connect('TroyData.db')
curs = conn.cursor()
v1 = curs.execute('''
SELECT acctvalue
FROM balancedata
WHERE acctno = ? ''', acctno)
print v1
conn.close()
When you pass SQLite a non-existing path, it'll happily open a new database for you, instead of telling you that the file did not exist before. When you do that, it'll be empty and you'll instead get a "No such table" error.
You are using a relative path to the database, meaning it'll try to open the database in the current directory, and that is probably not where you think it is..
The remedy is to use an absolute path instead:
conn = sqlite3.connect('/full/path/to/TroyData.db')
You need to loop over the cursor to see results:
curs.execute('''
SELECT acctvalue
FROM balancedata
WHERE acctno = ? ''', acctno)
for row in curs:
print row[0]
or call fetchone():
print curs.fetchone() # prints whole row tuple
The problem is the SQL statment. you must specify the db name and after the table name...
'''SELECT * FROM db_name.table_name WHERE acctno = ? '''
want to make small python module that can get data from a database. I have dowload pydbc and it worked fine like this:
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''')
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone()
Now i want to put this in a module so that i can import it and i dont need to write the code evrytime or locate the file. So i tried to create this like this
import pyodbc
def testDB():
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''')
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone()
return row
I saved it in: File "C:\Python27\lib\site-packages\testDB.py" and i tried to import it, but i got this error: SyntaxError: 'return' outside function
Im quite new to python, any ideas how i can put this as a module and be able to use import everytime i want to run that code?
As one of the comments says, your indentation is messed up. White space (indentation) is critical in Python. Try it like this:
import pyodbc
def testDB():
cnxn = pyodbc.connect("DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''")
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone()
return row
Also, you have to use double quotes for your connection string, since you are using single quotes in the string itself. I've changed them above in to reflect that.
good luck,
Mike
It's - for sqlplus - commands:
SQL> set serveroutput on
SQL> exec where.my_package.ger_result('something');
something=1823655138
And it's - for cx_Oracle:
>>> c.callproc('where.my_package.ger_result', ('something',))
['something']
As You can see - the results are different.
I have no idea, how to fix it. :[
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('my_ip_address_server_next_port', 0000, 'sid')
db = cx_Oracle.connect('user', 'password', dsn_tns)
curs = db.cursor()
curs.callproc("dbms_output.enable")
curs.callproc('where.my_package.ger_result', ['something',])
statusVar = curs.var(cx_Oracle.NUMBER)
lineVar = curs.var(cx_Oracle.STRING)
while True:
curs.callproc("dbms_output.get_line", (lineVar, statusVar))
if statusVar.getvalue() != 0:
break
print lineVar.getvalue()
Sorry, I can't reproduce this one.
I don't have your PL/SQL package, so I used the following stored procedure instead:
CREATE OR REPLACE PROCEDURE p_do_somet (
p_param IN VARCHAR2
) AS
BEGIN
dbms_output.put_line(p_param || '=1823655138');
END;
/
I got the same output, something=1823655138, from SQL*Plus and from using the Python script in your answer.
If you're getting different results using SQL*Plus and cx_Oracle, then either your stored procedure is doing something very funny (I don't know what could cause it to do this), or your SQL*Plus session and Python script are not connecting to the same database and/or schema.