Python - SQLite3 - Update not working via input - python

I try to Update my DB via Input.
import sqlite3
conn = sqlite3.connect('datenbank.db')
print ("Opened database successfully")
kunde1 = input("Der Kundename: ")
anzahl1 = input("Anzahl Bewertung: ")
conn.execute('''UPDATE kundenname SET anzahl = ? WHERE kundename = ?''',
(anzahl1, kunde1))
conn.commit
it dosent Show any Errors.. but it get not updated in DB?
Thanks a lot !

conn.commit does not call commit, rather, it is merely accessing its instance. Therefore, a simple commit call and a file close should fix the problem:
import sqlite3
conn = sqlite3.connect('datenbank.db')
print ("Opened database successfully")
kunde1 = input("Der Kundename: ")
anzahl1 = input("Anzahl Bewertung: ")
conn.execute('''UPDATE kundenname SET anzahl = ? WHERE kundename = ?''', (anzahl1, kunde1))
conn.commit()
conn.close()
since you are inputting data in the middle of the execution sequence, it may be better to use a contextmanager:
import contextlib
#contextlib.contextmanager
def update_database(kunde1, anzahl1):
conn = sqlite3.connect('datenbank.db')
print ("Opened database successfully")
yield conn #can be used later to update database in or outside the scope of "with"
conn.execute('''UPDATE kundenname SET anzahl = ? WHERE kundename = ?''', (anzahl1, kunde1))
conn.commit()
conn.close()
with update_database(input("Der Kundename: "), input("Anzahl Bewertung: ")) as b:
pass #do something after

Related

Why it's the else statement executed and if it's ignored?

I'm having a problem with a Python script, the if branch it's not executed, no matter what parameters I give to the script. Is it something wrong with my code? I'm executing an HTML form and the result was OK until I've added some content to the else statement..I've tried everything but it still doesn't want to work...
#!/usr/bin/python3
import pymysql
import cgi
from http import cookies
# Open database connection
db = pymysql.connect("localhost","superadmin","123","dinamic" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
data=cgi.FieldStorage()
a=data.getvalue('e1')
b=data.getvalue('p1')
# Prepare SQL query to fetch a record into the database.
sql = "SELECT id, email, password FROM register WHERE email = %s AND password = %s"
try:
# Execute the SQL command
cursor.execute(sql, (a, b))
# Commit your changes in the database
db.commit()
c=cookies.SimpleCookie()
# assign a value
c['mou']=a
# set the xpires time
c['mou']['expires']=24*60*60
# print the header, starting with the cookie
print (c)
print("Content-type: text/html", end="\r\n\r\n", flush=True);
print('''<html><head><title>First python script for Security and Encrpytion class</title></head><body><center><h2>Successfully login!</h2><br><img src='image/2.gif'></body></html>''');
except:
db.commit()
print("Content-type: text/html", end="\r\n\r\n", flush=True);
print("<html>");
print("<body>");
print("<center>")
print("<h2>Fail to login!</h2>");
print("<img src='image/dinamic.gif'>");
print("</body>");
print("</html>");
# Rollback in case there is any error
db.rollback()
cursor.execute() doesn't return the number of rows that were selected. You can call cursor.fetchone() to see if it returns a row.
There's also no need to call db.commit() since you haven't made any changes.
try:
# Execute the SQL command
cursor.execute(sql, (a, b)))
row = cursor.fetchone()
if row:
c=cookies.SimpleCookie()
# assign a value
c['mou']=a
# set the xpires time
c['mou']['expires']=24*60*60
# print the header, starting with the cookie
print (c);
print ("Content-type: text/html", end="\r\n\r\n", flush=True);
print("");
print('''<html><head><title>Security & Encryption class - First script</title></head><body><h2>successfully login!</h2>''');
print("<center>");
print("<img src='image/successfully.gif'>");
print("</center>");
print("</body></html>");
else:
print ("Content-type: text/html", end="\r\n\r\n", flush=True)
print("<html>")
print("<body>")
print("<center>")
print("<h2>Login fail!</h2>")
print("<img src='image/dinamic.gif'>")
print("<br><br>")
print('<button id="myButton" class="float-left submit-button" >Home</button>')
print('''<script type="text/javascript">
document.getElementById("myButton").onclick = function () {
location.href = "index.html";
};
</script>''');
print("</center>");
print("</body>");
print("</html>");
except:
# Rollback in case there is any error
db.rollback()

how to connect MySQL database to input function

I'm building a program, where the user input an enterprise's name to get the code running.
I would like the user to pick the enterprise name in a drop down list, but currently i dont have a GUI to make it work.
so for now, I would like to connect the input function to the SQL database enterprises name column.
I already connected SQL to my python code... but how do I connect MySQL to an input function? I want the user to be able to get the information from the database
MY SQL CONNECTION :
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="nn", passwd="passpass")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM listedatabase.entreprises_inspecteurs")
for row in mycursor.fetchall():
print (row[1])
mydb.close()
python:
enterprise_name = input()
Thank you for helping
I tried this but no luck:
mydb = mysql.connector.connect(host="localhost", user="nn", passwd="passpass")
mycursor = mydb.cursor()
enterprise_name = input()
mycursor.execute("SELECT n_fabricant FROM listedatabase.entreprises_inspecteurs", (enterprise_name,))
data = mycursor.fetchall()
if data:
code goes there
else:
print('data not found in database')
mydb = mysql.connector.connect(host="localhost", user="nn", passwd="passpass")
mycursor = mydb.cursor()
enterprise_name = input()
mycursor.execute("""SELECT n_fabricant FROM listedatabase.entreprises_inspecteurs WHERE n_fabricant = %s"""(event_inspecteur,))
data = mycursor.fetchall()
if data:
code goes there
else:
print('data not found in database')

pyodbc the sql contains 0 parameter markers but 1 parameters were supplied' 'hy000'

I am using Python 3.6, pyodbc, and connect to SQL Server.
I am trying make connection to a database, then creating a query with parameters.
Here is the code:
import sys
import pyodbc
# connection parameters
nHost = 'host'
nBase = 'base'
nUser = 'user'
nPasw = 'pass'
# make connection start
def sqlconnect(nHost,nBase,nUser,nPasw):
try:
return pyodbc.connect('DRIVER={SQL Server};SERVER='+nHost+';DATABASE='+nBase+';UID='+nUser+';PWD='+nPasw)
print("connection successfull")
except:
print ("connection failed check authorization parameters")
con = sqlconnect(nHost,nBase,nUser,nPasw)
cursor = con.cursor()
# make connection stop
# if run WITHOUT parameters THEN everything is OK
ask = input ('Go WITHOUT parameters y/n ?')
if ask == 'y':
# SQL without parameters start
res = cursor.execute('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN '2017-03-01T00:00:00.000' AND '2017-03-01T01:00:00.000'
''')
# SQL without parameters stop
# print result to console start
row = res.fetchone()
while row:
print (row)
row = res.fetchone()
# print result to console stop
# if run WITH parameters THEN ERROR
ask = input ('Go WITH parameters y/n ?')
if ask == 'y':
# parameters start
STARTDATE = "'2017-03-01T00:00:00.000'"
ENDDATE = "'2017-03-01T01:00:00.000'"
# parameters end
# SQL with parameters start
res = cursor.execute('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN :STARTDATE AND :ENDDATE
''', {"STARTDATE": STARTDATE, "ENDDATE": ENDDATE})
# SQL with parameters stop
# print result to console start
row = res.fetchone()
while row:
print (row)
row = res.fetchone()
# print result to console stop
When I run the program without parameters in SQL, it works.
When I try running it with parameters, an error occurred.
Parameters in an SQL statement via ODBC are positional, and marked by a ?. Thus:
# SQL with parameters start
res = cursor.execute('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN ? AND ?
''', STARTDATE, ENDDATE)
# SQL with parameters stop
Plus, it's better to avoid passing dates as strings. Let pyodbc take care of that using Python's datetime:
from datetime import datetime
...
STARTDATE = datetime(year=2017, month=3, day=1)
ENDDATE = datetime(year=2017, month=3, day=1, hour=0, minute=0, second=1)
then just pass the parameters as above. If you prefer string parsing, see this answer.
If you're trying to use pd.to_sql() like me I fixed the problem by passing a parameter called chunksize.
df.to_sql("tableName", engine ,if_exists='append', chunksize=50)
hope this helps
i tryied and have a lot of different errors: 42000, 22007, 07002 and others
The work version is bellow:
import sys
import pyodbc
import datetime
# connection parameters
nHost = 'host'
nBase = 'DBname'
nUser = 'user'
nPasw = 'pass'
# make connection start
def sqlconnect(nHost,nBase,nUser,nPasw):
try:
return pyodbc.connect('DRIVER={SQL Server};SERVER='+nHost+';DATABASE='+nBase+';UID='+nUser+';PWD='+nPasw)
except:
print ("connection failed check authorization parameters")
con = sqlconnect(nHost,nBase,nUser,nPasw)
cursor = con.cursor()
# make connection stop
STARTDATE = '11/2/2017'
ENDDATE = '12/2/2017'
params = (STARTDATE, ENDDATE)
# SQL with parameters start
sql = ('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN CAST(? as datetime) AND CAST(? as datetime)
''')
# SQL with parameters stop
# print result to console start
query = cursor.execute(sql, params)
row = query.fetchone()
while row:
print (row)
row = query.fetchone()
# print result to console stop
say = input ('everething is ok, you can close console')
I fixed this issue with code if you are using values through csv.
for i, row in read_csv_data.iterrows():
cursor.execute('INSERT INTO ' + self.schema + '.' + self.table + '(first_name, last_name, email, ssn, mobile) VALUES (?,?,?,?,?)', tuple(row))
I had a similar issue. Saw that downgrading the version of PyODBC to 4.0.6 and SQLAlchemy to 1.2.9 fixed the error,using Python 3.6

Update statement not working in python?

I've written a simple python program, which get Data form database successfully. but unable to update table in DB.
When executing update statement it's get stuck and nothing happen, no any exception.
My code is as follows. Any idea whyis this ?
from java.sql import DriverManager
def updateDB():
url = "jdbc:oracle:thin:#192.1.1.1:1521:auid"
uname = "dbtstj1"
pword = "dbtstj321"
conn = None
stmt = None
try:
conn = DriverManager.getConnection(url,uname,pword)
stmt = conn.createStatement()
rs = stmt.executeQuery("select PKG_NAME from PkgData")
while rs.next():
print rs.getString(1)
pkgName = "'Test Pkg Name'"
pkgID = "'T1234'"
updateQuary = "UPDATE PkgData SET PKG_NAME =%s WHERE PKG_ID =%s" %(pkgName, pkgID)
stmt.execute(updateQuary)
except Exception , e:
print 'Error:', e[0]
finally:
if stmt is not None:
stmt.close()
if conn is not None:
conn.close()
updateDB()
you need to commit your changes to the database:
stmt.execute(updateQuary)
conn.commit()
These type of issues can be happen when query request datatype and required datatype is difference.
It seems to be there was a mismatch with database's datatype and your query. Can you recheck with database's datatype with your query.
For Ex: PKG_ID =%s can be another data type in database as digit or etc...

TypeError: 'NoneType' object is not iterable

I need to process mysql data one row at a time and i have selected all rows put them in a tuple but i get the error above.
what does this mean and how do I go about it?
Provide some code.
You probably call some function that should update database, but the function does not return any data (like cursor.execute()). And code:
data = cursor.execute()
Makes data a None object (of NoneType). But without code it's hard to point you to the exact cause of your error.
It means that the object you are trying to iterate is actually None; maybe the query produced no results?
Could you please post a code sample?
The function you used to select all rows returned None. This "probably" (because you did not provide code, I am only assuming) means that the SQL query did not return any values.
Try using the cursor.rowcount variable after you call cursor.execute(). (this code will not work because I don't know what module you are using).
db = mysqlmodule.connect("a connection string")
curs = dbo.cursor()
curs.execute("select top 10 * from tablename where fieldA > 100")
for i in range(curs.rowcount):
row = curs.fetchone()
print row
Alternatively, you can do this (if you know you want ever result returned):
db = mysqlmodule.connect("a connection string")
curs = dbo.cursor()
curs.execute("select top 10 * from tablename where fieldA > 100")
results = curs.fetchall()
if results:
for r in results:
print r
This error means that you are attempting to loop over a None object. This is like trying to loop over a Null array in C/C++. As Abgan, orsogufo, Dan mentioned, this is probably because the query did not return anything. I suggest that you check your query/databse connection.
A simple code fragment to reproduce this error is:
x = None
for each i in x:
#Do Something
pass
This may occur when I try to let 'usrsor.fetchone' execute twice. Like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
if cursor.fetchone() is not None:
username, password = cursor.fetchone()
print username, password
I don't know much about the reason. But I modified it with try and except, like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
try:
username, password = cursor.fetchone()
print username, password
except:
pass
I guess the cursor.fetchone() can't execute twice, because the cursor will be None when execute it first time.
I know it's an old question but I thought I'd add one more possibility. I was getting this error when calling a stored procedure, and adding SET NOCOUNT ON at the top of the stored procedure solved it. The issue is that earlier selects that are not the final select for the procedure make it look like you've got empty row sets.
Try to append you query result to a list, and than you can access it. Something like this:
try:
cursor = con.cursor()
getDataQuery = 'SELECT * FROM everything'
cursor.execute(getDataQuery)
result = cursor.fetchall()
except Exception as e:
print "There was an error while getting the values: %s" % e
raise
resultList = []
for r in result:
resultList.append(r)
Now you have a list that is iterable.

Categories

Resources