Hi im having issues with a sql query it works perfect in console, but when i implement into python it seems to work perfect no errors but when i check the database it hasnt worked, yet with the console it does work the same no errors yet when i check db the data is there... exact same query i use.
Any ideas?
UPDATE ex SET fbsiteurl = stringvarible, fbsitesource = '' WHERE id = 23123;
in python:
cur = con.cursor()
sqlquery = "UPDATE ex SET fbsiteurl = '"+somevarible+"', fbsitesource = '"+somevarible+"' WHERE id = %d;" % recordid
print sqlquery
cur.execute(sqlquery)
query shows up fine in print no issues, if i copy the print out and paste it into a mysql console it works perfect everytime, just come python it acts like it works but dosnt really 0_o
connection.autocommit(), or you need to do connection.commit()
Been there :) you need to close the cursor
This little gotcha continues to this day. Just to clarify, I had to use both of the above answers, as in:
cur = self.db.cursor()
try:
cur.execute(sqlcommand)
self.db.commit()
res = cur.fetchall()
except res is not None:
print(res)
finally:
cur.close()
Related
I have written Python code to update my MySQL database via a for loop, however when I run the code, it does not insert the data into the table. Here is my code:
connection = mysql.connector.connect(\*\*db) # \*\*
cursor = connection.cursor()
for i in range(len(alumniNames)):
currentName = alumniNames[i]
query = (f'INSERT INTO alumni (name, address, hometown, state, country, home_phone, mobile_phone) VALUES ("{currentName}", "{alumniInfo[currentName][2]}", "{alumniCities[i]}", "{alumniStates[i]}", "{alumniInfo[currentName][5]}", "{alumniInfo[currentName][7]}", "{alumniInfo[currentName][8]}")')
values = (currentName, alumniInfo[currentName][2], alumniCities[i], alumniStates[i],
alumniInfo[currentName][5], alumniInfo[currentName][7], alumniInfo[currentName][8])
cursor.execute(query)
print(f"Query {i + 1} Completed.")
if i % 50 == 0:
time.sleep(1)
results = cursor.fetchall()
cursor.close()
connection.close()
When I run my code, no data gets inserted into the table. Also, the print statement stops at 331 (ex. "Query 331 Completed.").
I tried to googling the issue but I can't come to a conclusion as to why this is happening.
Based on your code, you're probably looking for autocommit configuration. If you're new to python + mysql, I'd recommend checking out SQL Alchemy and Alembic; it will level up your game.
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-autocommit.html
https://www.sqlalchemy.org/
https://alembic.sqlalchemy.org
Also, just for fun you can reduce the code a bit. I use enumerate all - the - time! :-)
# instead of range+len
for i, currentName in enumerate(alumniNames):
....
I am writing a script in python 3.x using mysqlconnector.
What I am trying to achieve right now is to check if there is a record inside my db which may be a duplicate to the one I am analyzing right now.
I came up with such code:
def fill_data(self, db_name, data):
cursor = self.cnx.cursor(buffered=True)
isDuplicate = cursor.execute(("SELECT destination FROM {0} WHERE destination = '{1}';")
.format(db_name, data['destination']))
print(cursor.statement)
self.commit()
print(isDuplicate is None)
Though I still get isDuplicate as None object. I tried to check via cursor.statement what statement is being passed to my db: it turned out that while in script I get None obj while passed in db that query works fine.
I also tried SELECT COUNT(1) FROM db_name which also gave me different results.
I am out of ideas: maybe you guys can help me out?
Update:
The solution that works for me was:
q = ("SELECT * FROM {0} WHERE destination = %s AND countryCode = %s AND prefix = %s")
.format(db_name)
cursor.execute(q, (data['destination'], data['country_code'], data['prefix']))
self.cnx.commit()
isDoubled = cursor.fetchone()
So at the end of the day it was all about fetching data from the cursor :)
Maybe the reason of your issue is the way you use execute() method.
Try to make some changes and see what is printed out:
def fill_data(self, db_name, data):
cursor = self.cnx.cursor(buffered=True)
q = 'SELECT count(*) FROM {} WHERE destination = %s'.format(db_name)
duplicate_count = cursor.execute(q, (data['destination'], )).fetchall()
print(duplicate_count)
Why should I provide query parameters this way? (article is on psql, but the core principles are the same as in mysql)
update
If you are still receiving "NoneType" object has no atribute "fetchall", then the error is probably here:
cursor = self.cnx.cursor(buffered=True)
Looks like you are not creating cursor at all. I can take a look at it if you post some code about cnx creation.
I am trying to fetch data from AWS MariaDB:
cursor = self._cnx.cursor()
stmt = ('SELECT * FROM flights')
cursor.execute(stmt)
print(cursor.rowcount)
# prints 2
for z in cursor:
print(z)
# Does not iterate
row = cursor.fetchone()
# row is None
rows = cursor.fetchall()
# throws 'No result set to fetch from.'
I can verify that table contains data using MySQL Workbench. Am I missing some step?
EDIT: re 2 answers:
res = cursor.execute(stmt)
# res is None
EDIT:
I created new Python project with a single file:
import mysql.connector
try:
cnx = mysql.connector.connect(
host='foobar.rds.amazonaws.com',
user='devuser',
password='devpasswd',
database='devdb'
)
cursor = cnx.cursor()
#cursor = cnx.cursor(buffered=True)
cursor.execute('SELECT * FROM flights')
print(cursor.rowcount)
rows = cursor.fetchall()
except Exception as exc:
print(exc)
If I run this code with simple cursor, fetchall raises "No result set to fetch from". If I run with buffered cursor, I can see that _rows property of cursor contains my data, but fetchall() returns empty array.
Your issue is that cursor.execute(stmt) returns an object with results and you're not storing that.
results = cursor.execute(stmt)
print(results.fetchone()) # Prints out and pops first row
For the future googlers with the same Problem I found a workaround which may help in some cases:
I didn't find the source of the problem but a solution which worked for me.
In my case .fetchone() also returned none whatever I did on my local(on my own Computer) Database. I tried the exact same code with the Database on our companies server and somehow it worked. So I copied the complete server Database onto my local Database (by using database dumps) just to get the server settings and afterwards I also could get data from my local SQL-Server with the code which didn't work before.
I am a SQL-newbie but maybe some crazy setting on my local SQL-Server prevented me from fetching data. Maybe some more experienced SQL-user knows this setting and can explain.
I am currently connecting to a Sybase 15.7 server using sybpydb. It seems to connect fine:
import sys
sys.path.append('/dba/sybase/ase/15.7/OCS-15_0/python/python26_64r/lib')
sys.path.append('/dba/sybase/ase/15.7/OCS-15_0/lib')
import sybpydb
conn = sybpydb.connect(user='usr', password='pass', servername='serv')
is working fine. Changing any of my connection details results in a connection error.
I then select a database:
curr = conn.cursor()
curr.execute('use db_1')
however, now when I try to run queries, it always returns None
print curr.execute('select * from table_1')
I have tried running the use and select queries in the same execute, I have tried including go commands after each, I have tried using curr.connection.commit() after each, all with no success. I have confirmed, using dbartisan and isql, that the same queries I am using return entries.
Why am I not getting results from my queries in python?
EDIT:
Just some additional info. In order to get the sybpydb import to work, I had to change two environment variables. I added the lib paths (the same ones that I added to sys.path) to $LD_LIBRARY_PATH, i.e.:
setenv LD_LIBRARY_PATH "$LD_LIBRARY_PATH":dba/sybase/ase/15.7/OCS-15_0/python/python26_64r/lib:/dba/sybase/ase/15.7/OCS-15_0/lib
and I had to change the SYBASE path from 12.5 to 15.7. All this was done in csh.
If I print conn.error(), after every curr.execute(), I get:
("Server message: number(5701) severity(10) state(2) line(0)\n\tChanged database context to 'master'.\n\n", 5701)
I completely understand where you might be confused by the documentation. Its doesn't seem to be on par with other db extensions (e.g. psycopg2).
When connecting with most standard db extensions you can specify a database. Then, when you want to get the data back from a SELECT query, you either use fetch (an ok way to do it) or the iterator (the more pythonic way to do it).
import sybpydb as sybase
conn = sybase.connect(user='usr', password='pass', servername='serv')
cur = conn.cursor()
cur.execute("use db_1")
cur.execute("SELECT * FROM table_1")
print "Query Returned %d row(s)" % cur.rowcount
for row in cur:
print row
# Alternate less-pythonic way to read query results
# for row in cur.fetchall():
# print row
Give that a try and let us know if it works.
Python 3.x working solution:
import sybpydb
try:
conn = sybpydb.connect(dsn="Servername=serv;Username=usr;Password=pass")
cur = conn.cursor()
cur.execute('select * from db_1..table_1')
# table header
header = tuple(col[0] for col in cur.description)
print('\t'.join(header))
print('-' * 60)
res = cur.fetchall()
for row in res:
line = '\t'.join(str(col) for col in row)
print(line)
cur.close()
conn.close()
except sybpydb.Error:
for err in cur.connection.messages:
print(f'Error {err[0]}, Value {err[1]}')
I have a problem with deleting a record from my SQLite3 database:
conn = sqlite3.connect('databaza.db')
c = conn.cursor()
data3 = str(input('Please enter name: '))
mydata = c.execute('DELETE FROM Zoznam WHERE Name=?', (data3,))
conn.commit()
c.close
Everything is OK, no errors, but the delete function doesn't work!
Does anyone have an idea?
The correct syntax for a parameterized query is:
mydata = c.execute("DELETE FROM Zoznam WHERE Name=?", (data3,))
Make sure the parameter uses the comma, to make it a python tuple.
This will help prevent SQL Injection which is possible when passing in a formatted string. More on SQL Injection here
Related post here.
I'm a little late to the party but if you Google search "python sqlite delete row" This is the first thing that comes up and I was having the same issue where things were not getting DELETE'd from my sqlite DB.
I'm using Python 2.7 on Debian Jessie.
Previously, when I wrote Python code for adding and retrieving information in the sqlite database, I had written the commands with correct capitalization where needed and it worked.
curs.execute("SELECT example_column1 FROM example_table WHERE example_column2=(?)", (Variable,))
However...
curs.execute("DELETE FROM example_table WHERE example_column1=(?)", (Variable,)):
This for some reason does not work with the DELETE command. I had to send that command in all lower-case before sqlite would respect the command being sent.
conn=sqlite3.connect('example.db')
curs=conn.cursor()
curs.execute("delete from example_table where example_column=(?)", (Variable,))
conn.commit()
conn.close()
I have no idea why.
I tried all the previously mentioned methods but having the command sent in lowercase was the only way I could get it to work.
Hope this helps any struggling neophytes in their journey into Python and sqlite.
Try with:
mydata = c.execute('DELETE FROM Zoznam WHERE Name = (?)', (data3))
Without the ',' and the '?' between '()'
I'm using Python 3.9 on windows.
c.execute("DELETE FROM Zoznam WHERE Name={0}".format(data3))
conn.commit()
I advise you to first make a string for the query , and then execute it. ex:
query = "delete from zoznam where name = '%s' " % data3
c.execute(query)
conn.commit()
Check the file permissions.
An aside, I prefer the tokenized method:
mydata = c.execute("DELETE FROM Zoznam WHERE Name='%s'" % data3)
Thank you to everybody who tried to help. The right code is:
conn = sqlite3.connect('databaza.db')
c = conn.cursor()
conn.text_factory = str
data3 = str(input('Please enter name: '))
query = "DELETE FROM Zoznam WHERE Name = '%s';" % data3.strip()
print(query)
mydata = c.execute(query)