Inserting data into MySQL DB using Python [duplicate] - python

This question already has an answer here:
Why isn't the 'insert' function adding rows using MySQLdb?
(1 answer)
Closed 5 years ago.
I want to insert data to Mysql database using python. Here is my code
def insert_db(time_spent):
global user_id
global total_time_spent
user = user_id
project = get_project_id()
timesingle = time_spent
timeall = total_time_spent
#connect to the database
connect_db = mysql.connector.connect(user='root',password='',host='127.0.0.1',database='python_test')
cursor = connect_db.cursor()
cursor.execute("INSERT INTO time (user_id,project_id,spent_time,total_time) VALUES (%s,%s,%s,%s)",(user,project,timesingle,timeall)) # insert new row to table
if cursor.lastrowid:
print('last insert id', cursor.lastrowid)
else:
print('last insert id not found')
#close the cursor and database connection
cursor.close()
connect_db.close()
The problem is when I execute this function, even 'last insert row id' is showing the id, the data is not inserting to the database. I checked all the variables in this function and they are not empty.
How can I fix this issue

Everytime you modify data in your database you need to commit all the changes with.
connect_db.commit();
This is to ensure that you only save changes where no errors happened.

You need to commit to marks the end of a successful transaction.
connect_db.commit()
For further information: https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html

Please ensure that you use connect_db.commit() after every insert/update or other such statements.

Related

How to insert variable to sql table in python if variable is not already in table? [duplicate]

This question already has answers here:
SQLite INSERT - ON DUPLICATE KEY UPDATE (UPSERT)
(5 answers)
Closed 6 months ago.
Im having a problem with my sqlite database in my python program. I'm trying to create a table that will hold records of players score. Player name is saved as variable "val" and that variable is used in sql code. Also if the player is already in my table I don't want to create duplicate.
My problem is that if I don't use WHERE {v}... it all works, but the moment i try to prevent table from creating duplicates it gives me an OperationalError: near "WHERE": syntax error.
Im quite new to sql so it's hard for me to find what i'm doing wrong. I used (?) and format and as long as i don't use WHERE it's fine. How can I make sure that my variable (player name) from outside of sql code is not in my table so i can insert it?
val = "PlayerName"
cur.execute( """
INSERT INTO Table (player_name)
VALUES {v}
WHERE {v} NOT IN (
SELECT player_name FROM Table)""".format(v = val))
Ok, it works now. My main problem was that i tried to use commands from MySQL instead of sqlite. My code that worked:
cur.execute( """INSERT INTO Table (player_name)
VALUES (?)
ON CONFLICT(player_name) DO UPDATE SET player_name= player_name""",(val) )
Edit: Final version without player_name = player_name workaround:
cur.execute( """INSERT OR IGNORE INTO Table (player_name) VALUES (?)""",(val) )

Updating an SQL table while searching another SQL table

I have an SQL database "Garage.db" that has 3 tables:
Customer, Car and MOT
I want to update the field BookedMOT in the MOT table when someone has entered a Registration that is in the Car table. Can someone help me with the SQL query that can do this, thank you.
I am coding this in python 3.6 using tkinter. Here is my attempt,
def Booked(self):
date = Date.get()
month = Month.get()
year = Year.get()
BookedMOT = (date + '/' + month + '/' + year)
Registration = self.RegistrationEnt.get()
with sqlite3.connect('Garage.db') as db:
cursor = db.cursor()
add_date = ('UPDATE MOT SET MOT.BookedMOT = ? FROM Car WHERE Car.Registration = ?')
cursor.execute(add_date,[(BookedMOT), (Registration)])
db.commit()
(this addresses some Python problems I noticed before even realising that the SQL didn't look right, which should probably be fixed first)
Try this:
with sqlite3.connect('Garage.db') as db:
db.execute(add_date, (BookedMOT, Registration))
In general, when you say with ... as x:, you should probably use x inside the with block. After the block finished it did an automatic commit and trying to use db or cursor afterwards is probably incorrect. The with also means that you don't have to db.commit() any more.
sqlite3 connection objects (db in this case) have an execute method:
This is a nonstandard shortcut that creates a cursor object by calling the cursor() method, calls the cursor’s execute() method with the parameters given, and returns the cursor.
Finally, you had some redundant parentheses that could be removed.

Table won't alter when using psycopg

I'm having some trouble altering tables in my postgres database. I'm using psycopg2 and working out of Python. I tried to add a serial primary key. It took a long time (large table), and threw no error, so it did something, but when I went to check, the new column wasn't there.
I'm hoping this is something silly that I've missed, but right now I'm at a total loss.
import psycopg2
username = *****
password = *****
conn = psycopg2.connect(database='mydb',user=username,password=password)
query = "ALTER TABLE mytable ADD COLUMN sid serial PRIMARY KEY"
cur = conn.cursor()
cur.execute(query)
conn.close()
Other things I've tried while debugging:
It doesn't work when I remove PRIMARY KEY.
It doesn't work when try a different data type.
You need to add a commit statement in order for your changes to reflect in the table. Add this before you close the connection.
conn.commit()

Python Update in MySQL

I've been struggling to get this really simple query to actually work in Python. I am a complete python newb, and strings seem to be handled a lot differently than what I am accustomed to.
The query I am trying...
cur = db.cursor()
cur.execute("SELECT bluetooth_Id FROM student_Data")
data = cur.fetchall()
for row in data :
bluetoothId=row[0]
result=bluetooth.lookup_name(bluetoothId,timeout=5)
print(result)
if(result != None):
cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s",(bluetoothId))
print("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s",(bluetoothId))
What seems to be the problem is that my actual SQL query is not correctly formatted.. I know this because that last print statement returns this
('UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s', 'th:is:is:my:bt:id')
and of course that id is not actually the id it returns... I didn't want to give that to you :)
I am following examples to the dot, and not getting anywhere.. my bluetooth is on, the program sees my bluetooth id, it processes through the list of ids already in my mysql table, but it isn't updating any records.
and I did check to make sure I entered my id in the mysql table correctly, so that is not the problem either!
Update
I was able to get the correct MySQL query created using this:
cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '%s"%(bluetoothId)+"'")
which creates
UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '11:11:11:11:11:11'
but the MySQL table still isn't updating correctly.. I'll have to look into seeing why that is...
The solution was this:
cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '%s"%(bluetoothId)+"'")
and then I had to add
db.commit()
After the execute, in order to actually commit the changes to the MySQL table.
Thanks all for the help:)
Python mySQL Update, Working but not updating table
You need to do this:
cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s"%(bluetoothId))
If you are doing substitution, you need a % instead of a comma

Multiple python connections to same sqlite Database table [duplicate]

This question already has answers here:
Can SQLite support multiple users?
(3 answers)
Closed 7 years ago.
I am trying write two processes using python that require access to same sqlite database table. One of the process updates the table by inserting new data and the other process retrieves information from the same table. However when the other second process runs select query the data base is already locked and I get
the "OperationalError: database is locked". Following are the code for both processes. Appreciate any help
process : 1
------------
while True:
print "Updating"
try:
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute('PRAGMA journal_mode = WAL')
c.executemany('INSERT INTO test_table VALUES (?,?,?,?,?)', insertdata)
conn.commit()
conn.close()
except:
pass
time.sleep(60)
process : 2
------------
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("select * from test_table where id='{}' and date = '{}' order by time desc".format(recv_data,datetime.datetime.now().date().isoformat()))
data= c.fetchall()
conn.close()
The link given above only suggests that multiple connection in sqlite is possible. However it doesn't suggest how to do it
The database blocks the access after any writing operation during some milliseconds hence you can try a time.sleep(1) in the process: 2 to avoid this collision at least the first time.

Categories