Why does a mySQL Python Query not insert a new entry? - python

So I am trying to add a new entry into my mySQL Database.
The problem here is, that it increases the id, but does add the entry.
After a little bit of googling I found that a failed INSERT query also increases the AUTO_INCREMENTd value (id in my case).
The mySQL Table is created using
CREATE TABLE IF NOT EXISTS TS3_STAMM_1 (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(64) NOT NULL, ts3_uid VARCHAR(64) NOT NULL, points INT(8) UNSIGNED NOT NULL); which is called by the function qServer.execute(querystring) inside python's MySQLdb module.
Then I use qString = "INSERT INTO TS3_STAMM_1 (name, ts3_uid, points) VALUES ('{}', '{}', {})".format(name, uid, pnts) (the datatypes are correct, I at least quadrouplechecked) with the function qServer.exectue(qString) to insert a new entry into the database.
But it is incrementing the ID, but its not adding an entry. So my guess would be its a failed query, but why? How does it happen? How to fix it?
Simple SELECT querys work fine the same way, also adding data manually works fine. Only the python query fails.
Note: qServer is the connection to the server, and its defined with:
try:
qConn = MySQLdb.connect(host="...", user="...", passwd="...", db="...")
qServer = qConn.cursor()
except OperationalError:
print("Cannot connect to mySQL Database! Aborting...")
exit(1)

Use commit Luke.
>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)", ('Jane', ))
>>> qConn.commit()
Using str.format for creating SQL query is bad idea.

Related

Why when I try create table in SQLite by python it shows me: error near "<": syntax error

I test commands for sql by python. Generaly everything is okey, in this case, its doesn't work.
import sqlite3
conn = sqlite3.connect('Chinook_Sqlite.sqlite')
cursor = conn.cursor()
result = None
try:
cursor.executescript("""CREATE TABLE <New>;""")
result = cursor.fetchall()
except sqlite3.DatabaseError as err:
print("Error: ", err)
else:
conn.commit()
print(result)
conn.close()
Name writes with out <> and must include: name, type, default value after in ().
https://www.sqlite.org/lang_createtable.html - thanks #deceze
The "CREATE TABLE" command is used to create a new table in an SQLite
database. A CREATE TABLE command specifies the following attributes of
the new table:
he name of the new table.
The database in which the new table is created. Tables may be created in the main database, the temp database, or in any attached
database.
The name of each column in the table.
The declared type of each column in the table.
A default value or expression for each column in the table.
A default collation sequence to use with each column.
Optionally, a PRIMARY KEY for the table. Both single column and composite (multiple column) primary keys are supported.
A set of SQL constraints for each table. SQLite supports UNIQUE, NOT NULL, CHECK and FOREIGN KEY constraints.
Optionally, a generated column constraint.
Whether the table is a WITHOUT ROWID table.
cursor.executescript("""CREATE TABLE New ( AuthorId INT IDENTITY (1, 1) NOT NULL, AuthorFirstName NVARCHAR (20) NOT NULL, AuthorLastName NVARCHAR (20) NOT NULL, AuthorAge INT NOT NULL);""")

ID is not autoincrementing in my sqlite3 database

I am trying to build a GUI CRUD app in python where a user enters an object; say an apple the amount of objects (10) and the date at which they conducted their research could be today or yesterday etc (29/03/2021) in this format.
This data then gets sent to a sqlite3 database so reports can be run.
When implementing and the python file the sqlite database contains all the information added bar the ID which should be autoincremented, instead it shows NULL.
import sqlite3
class Database:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS errors (ID INTEGER PRIMARY KEY AUTOINCREMENT,
Subject text, Total integer, Date text)")
self.conn.commit()
def insert(self, subject, total, date):
self.cur.execute("INSERT INTO errors VALUES (NULL, ?, ?, ?)", (subject, total, date))
self.conn.commit()
So basically my ID column is not incrementing and is saying NULL. I have tried removing "AUTOINCREMENT" aswell as some say it is not necessary with PRIMARY KEY PRESENT but still doesn't work.
Well yes, autoincrement ids only works when sqlite is creating the value. Here you're giving it NULL explicitely so it does as you ask and uses NULL.
If you want the default behaviour, just don't provide a value for that column:
insert into errors (subject, total, date) values (?, ?, ?)
unlike postgres, sqlite apparently doesn't support DEFAULT pseudo-expressions, so that seems to not be an option.
Incidentally, the AUTOINCREMENT is probably why sqlite doesn't error on NULL:
According to the SQL standard, PRIMARY KEY should always imply NOT NULL. Unfortunately, due to a bug in some early versions, this is not the case in SQLite. Unless the column is an INTEGER PRIMARY KEY or the table is a WITHOUT ROWID table or the column is declared NOT NULL, SQLite allows NULL values in a PRIMARY KEY column.
meaning a column which is strictly declared as INTEGER PRIMARY KEY should implicitly reject NULL values, as it will make the column an alias / replacement for the implicit ROWID.

Python ODBC Create Table IF Not Exists

I have a SQL ODBC statement in Python but it always returns an error. On the SQL Server the statement works fine. Can anyone help me here?
execute("IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='tablename' AND xtype='U')
CREATE TABLE tablename (id INTEGER PRIMARY KEY, fieldA NVARCHAR(Max) NOT NULL, fieldB NVARCHAR(Max) NOT NULL)")
EDIT: Please note that you have to use triple quotations for multi-line string in Python, if the execute statement is pasted above as written in your script it most likely fails from the newline.
execute("""IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='tablename' AND xtype='U')
CREATE TABLE tablename (id INTEGER PRIMARY KEY, fieldA NVARCHAR(Max) NOT NULL, fieldB NVARCHAR(Max) NOT NULL)""")
I recommend just using the pandas to_sql function. It will create the table with all necessary columns in case it does not exist.
You can use the if_exists parameter to handle an already existing table ('append'/'replace'/'fail')

my python code write in a temporary data base

I wrote a python code that write/read data in/from a MySQL DB. The problem is that the table still empty even after I write in it. And when I close the program I loose all the data.
this is how I created the tables:
cursor.execute("CREATE TABLE IF NOT EXISTS employees (id INT UNSIGNED NOT NULL AUTO_INCREMENT,Name VARCHAR(20) NOT NULL,LastName VARCHAR(20) NOT NULL,Post VARCHAR(20) NOT NULL,RasID SMALLINT UNSIGNED NOT NULL,PRIMARY KEY (id)) ENGINE=INNODB;")
this is how I insert data in the tables:
cursor.execute("INSERT INTO employees VALUES (NULL, %s, %s, %s, %s);",(UserName, UserLastName, UserPost, int(data['RasID'])))
and this how I select data from the tables:
cursor.execute("SELECT * FROM employees WHERE Name= %s;",(Jmsg['face'],))
this what I get after inserting data in the table and the program still running:
mysql> select * from employees;
Empty set (0.00 sec)
NB: I can select data after inserting it when the program still running but as I mentioned the table is empty. So, is the code write in a temporary table or what?
Try
connection.commit()
MySQL Connector/Python, which you're probably using here, does not autocommit which means that you have do it manually to "push" changes to database.
You may want to commit after every execute but you may also try to run it sometimes to conserve your bandwidth (but then you risk that you lose your changes when something went wrong).
A transaction in a database takes generally no effect until it is commited.
I don't know about MySQL in Python, but I do know that sqlite3's Connection instances have a commit method, that will write the transaction into the database.
In addition, when working with sqlite3, closing the connection by calling Connection.close() or (by leaving a with block, I think) should write the current transaction.
But anyway, it's bad practice to leave an object that was opened open.
And by "bad practice", I mean "dangerous and prone to bugs".

How can I insert this on my table?

Creating my table:
cursor.execute("""
CREATE TABLE if not exists intraday_quote (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
symbol VARCHAR(10) NOT NULL,
date DATE,
time DATE,
open FLOAT,
high FLOAT,
low FLOAT,
close FLOAT,
volume INTEGER);
""")
and I`m trying to insert this:
conn = sqlite3.connect('intraday_quote.db')
cursor = conn.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO intraday_quote(symbol) VALUES ('Mac123432')"""
cursor.execute(sql)
No insertion happened in the database. What I am missing?
You need to commit your changes so they can get into effect in database.
commit all db operations like update, insert.
cursor.commit()
after your execute is succeeded. You can get return of the cursor.execute. If it is not None then you can try committing the changes else use rollback(exercise for you :) ) so you wont end up with wrong data updated in database.
You need to do conn.commit() to see the changes in the database. Quoting the documentation
This method commits the current transaction. If you don’t call this method, anything you did since the last call to commit() is not visible from other database connections. If you wonder why you don’t see the data you’ve written to the database, please check you didn’t forget to call this method.

Categories