I'm having an issue getting my python script to update my sqlite db.
The first part seems to work fine:
conn = sqlite3.connect('/Users/test/Desktop/my-accounts.db')
currentAccount = None
for row in conn.execute('SELECT email FROM accounts WHERE active=0'):
currentAccount = row[0]
print "Checking out: ",currentAccount
break
if currentAccount is None:
print "No available accounts"
Then this next part I want to take the variable currentAccount and update the row in the db where that value is.
else:
conn.execute('UPDATE accounts SET active=1 WHERE email=?', [currentAccount,])
conn.close()
I don't get any errors in the console but the db does not update. The email column is a VARCHAR and the active column is an INT.
Thanks.
SOLUTION was to add
conn.commit() after execute()
try to add conn.commit() after conn.execute("XXX"). Sometimes sqlite3 doesn't auto commit the execution.
Related
I am new to MYSQL and i am facing a very easy problem with MYSQL. I am creating a database that contains a school table , this table contains the sschool's name , contact, address, ID( primary key) . I need to delete a record based on the user's choice of id ( call this variable school_id) , so how to write this in a mysql statement using python ? i have tried this but i know it is wrong -->
print "Delete school"
school_id = int(input('Please, enter an ID: '))
cursor.execute("DELETE FROM `schools` WHERE id = %s", (school_id,))
its no deleting.whats the error
Have you committed the delete?
cursor.commit()
As already said by joof most likely you haven't commited the change.
If it doesn't help I'd try first to execute this statment in mysql and see if it works, then check if you have right connection to your db.
Link to using sql in Python.
https://docs.python.org/3.6/library/sqlite3.html
Unless you commit, it won't be executed:
cursor.commit()
Have fun.
print "Delete school"
school_id = int(input('Please, enter an ID: '))
cursor.execute("DELETE FROM `schools` WHERE id = %s", (school_id,))
From MySQL documentation on commit:
it is important to call this method after every transaction that modifies data for tables that use transactional storage engines.
You don't have to use it after literally every transaction - it's enough if you call it once after all execute are called:
def a():
cursor.execute('insert ...') # cursor object
cursor.execute('update ...')
connection.commit() # connection object
def b():
cursor.execute('delete ...')
connection.commit()
I'm using pypyodbc with SQL Server 2016.
I am trying to insert and grab the last id inserted into database following another user's remarks but the returned value seems to be encrypted. Is there a way to decrypt it?
def executeSQL (command):
connection = pypyodbc.connect('Driver={SQL Native Client};'
'Server=blah\blah;'
'Database=Impact;'
'uid=Admin;pwd=F$sfgdfgs99')
cursor=connection.cursor()
cursor.execute(command)
id = cursor.execute("SELECT ##IDENTITY")
connection.commit()
connection.close()
return id
sqlexecute = 'INSERT INTO PERSONS([LastName], [FirstName]) VALUES(\''+lastname.encode('utf-8')+'\',\''+firstname.encode('utf-8')+'\');\n'
lastid = executeSQL(sqlexecute)
print lastid
Output:
<pypyodbc.Cursor instance at 0x000000000B870C88>
It is not encrypted, it is telling you the type of the object that this is an instance of. In this case, it is pypyodbc.Cursor.
To fetch the actual rows, you do id.fetchall() which will return a list of the results. You can then loop over them to read the contents.
I am inserting a couple thousand records into a table via the python code below:
values = ''
for row in cursor:
values = values + "(" + self.quoted_comma_separate(row) + "),"
values = values[:-1]
insert_statement = "INSERT INTO t1 ({0}) VALUES {1};".format(
self.comma_separate(members), values)
db = Database()
conn = db.get_db()
cursor = conn.cursor()
cursor.execute(insert_statement)
conn.commit()
conn.close()
When I check the database after it runs none of the records show up in the database. If I go into an MySQL editor and manually commit the transaction all of the records appear. Why is my conn.commit() not working?
The insert statements were fine. Turns out I had another database connection open and it was getting confused and committing to the wrong connection or something like that. Sorry for the pointless question :)
I'm new to mySQL and Python.
I have code to insert data from Python into mySQL,
conn = MySQLdb.connect(host="localhost", user="root", passwd="kokoblack", db="mydb")
for i in range(0,len(allnames)):
try:
query = "INSERT INTO resumes (applicant, jobtitle, lastworkdate, lastupdate, url) values ("
query = query + "'"+allnames[i]+"'," +"'"+alltitles[i]+"',"+ "'"+alldates[i]+"'," + "'"+allupdates[i]+"'," + "'"+alllinks[i]+"')"
x = conn.cursor()
x.execute(query)
row = x.fetchall()
except:
print "error"
It seems to be working fine, because "error" never appears. Instead, many rows of "1L" appear in my Python shell. However, when I go to MySQL, the "resumes" table in "mydb" remains completely empty.
I have no idea what could be wrong, could it be that I am not connected to MySQL's server properly when I'm viewing the table in MySQL? Help please.
(I only use import MySQLdb, is that enough?)
use commit to commit the changes that you have done
MySQLdb has autocommit off by default, which may be confusing at first
You could do commit like this
conn.commit()
or
conn.autocommit(True) Right after the connection is created with the DB
I am trying to add all words of a text file into a column such that one row has one word. my code is as :
import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root", db = "pcorpora")
c = conn.cursor()
file = open('C:\Users\Admin\Desktop\english.txt', 'r')
words = list(file.read())
i=0
for value in words:
c.execute("""INSERT INTO tenglish (`english words`) VALUES (%s)""" % (words[i]) i=i+1)`
The code run without error but table is still empty.
You should use commit
c.execute("""INSERT INTO tenglish (`english words`) VALUES (%s)""" % (value))
con.commit()
This method sends a COMMIT statement to the MySQL server, committing
the current transaction. Since by default Connector/Python does not
autocommit, it is important to call this method after every
transaction that modifies data for tables that use transactional
storage engines.