Printing an sqlite selection in Python 3 - python

So I just started working with sqlite in Python (and I am a beginner with Python as well), and I'm struggling with using the data from a Table.
Basically, I created my database but now I would like to do something with the data. I have tried just simply printing it using this function:
def Select():
surname = input("Whose birthdate would you like to know? (surname)\n")
print(c.execute("SELECT Birthday FROM People WHERE Surname=?", (surname,)))
but this is what gets printed when I call on the function.
<sqlite3.Cursor object at 0x0000020825545F10>
Anybody know what the fix for this is?
Thanks in advance!

You have to use fetchone function of the cursor to get one record or you can use fetchall to get all the row of the query.

Try using the method fetchone or fetch many.
print(c.fetchone())
or
print(c.fetchmany())
you can see the documentation here.

Related

Python Mysql get variable value after select completes

So I am trying to do an IF statement after the select is done in python. Hard to explain, better to provide an example of it:
customer = cursor.execute("SELECT * FROM customer")
try:
customer['name']="john"
(do something here)
except:
customer['name']!="john"
(do something else here)
I hope this makes sense and sorry if this is not enough information. Trying to think of how to explain this. I don't want it to do a WHERE statement in the select because I don't want it to NOT SELECT certain information just because their 'name' is not "john"
First of all, you are not telling us which library you are using for working with MySQL. I assume its MySQLdb.
After executing SQL query with cursor.execute you have to call fetchall or fetchone. In later case you will be able to do customer['name'].
Example:
results = cursor.execute("SELECT * FROM customers")
customer = cursor.fetchone()
You shouldn't be using try/except since there is not an obvious case when any exception is thrown or is expected.

python pypyodbc writing to dBase not working

Have a terrible time trying to get this working. Spent way too many hours doing searches only to come up with the same examples which are not helping.
Made myself a GUI that starts a Thread to read the serial ports and parse some GPS data into NMEA sentences.
I take the data and want to write it to a database instead of a text file just to make it cleaner. However, when I write to the DB it throws an error saying that:
'type' object has no attribute '__getitem__'
As I have zero experience dealing with databases and python I'm at an impass as to what is wrong.
I know its the cur.execute INSERT line tossing the exception, I just don't know how to fix it.
Anyone care to walk me through it? I'm guessing it might be syntax? I'm using the pynmea2 module for GPS parsing and the pypyodbc module to make the MDB file.
If I write hard-coded-data it works fine. It's when I use variables that it craps out.
try:
print ("Attempt to Execute...")
Ndx=ID;Tod=str(gps_msg.timestamp);Lat=str(gps_msg.latitude);Lon=str(gps_msg.longitude);TmpLat='0';TmpLon='0';Alt=str(gps_msg.altitude);Flags='0';SystemID=str(gps_msg.ref_station_id);NumSat=str(gps_msg.num_sats);dop='0';Ch1_RSSI=str(rssi_dB)
cur.execute("INSERT INTO LogFile(Ndx,Tod,Lat,Lon,TmpLat,TmpLon,Alt,Flags,SystemID,NumSat,dop,Ch1_RSSI) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",([Ndx],[Tod],[Lat],[Lon],[TmpLat],[TmpLon],[Alt],[Flags],[SystemID],[NumSat],[dop],[Ch1_RSSI]))
print ("Attempting to commit...")
conn.commit()
print ("Commit succeeded..")
ID = ID + 1
except Exception as e:
errorLog.writelines('File Write Failure: {0}'.format(e)+"\n")
You are trying to pass the parameter values as a tuple whose elements are single-item lists. That won't work. The parameters must be passed as a list (or tuple) of individual values or objects.
So, instead of passing
([Ndx],[Tod],[Lat], ... )
you should be passing
[Ndx,Tod,Lat, ... ]
as the second argument to the .execute() method.

Python Database update error

Usually i use Django orm for making database related query in python but now i am using the python itself
I am trying to update a row of my mysql database
query ='UPDATE callerdetail SET upload="{0}" WHERE agent="{1}" AND custid="{2}"AND screenname="{3}" AND status="1"'.format(get.uploaded,get.agent,get.custid,get.screenname)
But i am getting the error
query ='UPDATE callerdetail SET upload="{0}" WHERE agent="{1}" AND custid="{2}"AND screenname="{3}" AND status="1"'.format(get.uploaded,get.agent,get.custid,get.screenname)
AttributeError: 'C' object has no attribute 'uploaded'
Please help me what is wrong with my query ?
Get is probably mapping to a c object. Try renaming your "get" object to something else.
Here is a list of reserved words. I don't see get in there, but it sound like it could be part of a c library that's being included. If you're including something with from x import *, you could be importing it without knowing.
In short - get probably isn't what you think it is.
However, before you go much further building SQL queries with string formatting, I strongly advise you not to! Search for "SQL injection" and you'll see why. Python DB API compliant libraries utilise "placeholders" which the library can use to insert the variables into a query for you providing any necessary escaping/quoting.
So instead of:
query ='UPDATE callerdetail SET upload="{0}" WHERE agent="{1}" AND custid="{2}"AND screenname="{3}" AND status="1"'.format(get.uploaded,get.agent,get.custid,get.screenname)
An example using SQLite3 (using ? as a placeholder - others use %s or :1 or %(name)s - or any/all of the above - but that'll be detailed in the docs of your library):
query = "update callerdetail set upload=? where agent=? and custid=? and screename=? and status=?"
Then when it comes to execute the query, you provide the values to be substituted as a separate argument:
cursor.execute(query, (get.uploaded, get.agent, get.custid, get.screenname))
If you really wanted, you could have a convenience function, and reduce this to:
from operator import attrgetter
get_fields = attrgetter('uploaded', 'agent', 'custid', 'screenname')
cursor.execute(query, get_fields(get))

python postgis ST_Contains failing query

I have been trying the following but always fails,
roomTypeSQL = "SELECT spftype FROM cameron_toll_spatialfeatures WHERE ST_Contains(ST_GeomFromText(%s), ST_geomFromWKB(geometry)) = 'True';"
roomTypeData = (pointTested) # "POINT(-3.164005 55.926378)"
.execute(roomTypeSQL, roomTypeData)
I want to get the polygon from my table which contains the specific point. I have also tried ST_Within which also fails. I think my problem is related to the formatting of the point and polygon but I have tried almost all combinations and nothing does the job. I tried defining my polygon and it worked but I must do it with a polygon from the database. My postgresql log file is not particularly helpful either..
Can anybody see anything going wrong?
Thanks in advance!
might be a simple answer...st_contains returns 't' not 'true'. Postgres is cap sensitive, make sure t not T
This had to do with python operators. I entered all the sql arguments using the python % operator properly and it worked. Like this,
roomTypeSQL = "SELECT spftype FROM cameron_toll_spatialfeatures WHERE ST_Contains(ST_GeomFromText(%s),ST_geomFromWKB(geometry))=%s;"
roomTypeData = (pointTested,'t') # "POINT(-3.164005 55.926378)"
.execute(roomTypeSQL, roomTypeData)
The python operator can be quite frustrating sometimes. It doesn't always work as expected. I have some examples of SQL commands in which I had to place the arguments directly inside SQL commands. This method worked although its not advisable in Python documentation.

How to a query a set of objects and return a set of object specific attribute in SQLachemy/Elixir?

Suppose that I have a table like:
class Ticker(Entity):
ticker = Field(String(7))
tsdata = OneToMany('TimeSeriesData')
staticdata = OneToMany('StaticData')
How would I query it so that it returns a set of Ticker.ticker?
I dig into the doc and seems like select() is the way to go. However I am not too familiar with the sqlalchemy syntax. Any help is appreciated.
ADDED: My ultimate goal is to have a set of current ticker such that, when new ticker is not in the set, it will be inserted into the database. I am just learning how to create a database and sql in general. Any thought is appreciated.
Thanks. :)
Not sure what you're after exactly but to get an array with all 'Ticker.ticker' values you would do this:
[instance.ticker for instance in Ticker.query.all()]
What you really want is probably the Elixir getting started tutorial - it's good so take a look!
UPDATE 1: Since you have a database, the best way to find out if a new potential ticker needs to be inserted or not is to query the database. This will be much faster than reading all tickers into memory and checking. To see if a value is there or not, try this:
Ticker.query.filter_by(ticker=new_ticker_value).first()
If the result is None you don't have it yet. So all together,
if Ticker.query.filter_by(ticker=new_ticker_value).first() is None:
Ticker(ticker=new_ticker_value)
session.commit()

Categories

Resources