Python sqlite3 insert only works in console - python

I have a simple insert statement in sqlite3, but somehow the python version doesn't work, but the exact same statement works fine in console. And python doesn't show any insert error. Any suggestion on how to fix this insert statement in python?
Insert statement:
INSERT INTO facilities (facility_id,facility_name) VALUES ('239SIE39', 'Lobby A');
Table creation statement:
CREATE TABLE IF NOT EXISTS facilities (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, facility_id, facility_name)
Function to store data:
def store_data(table_name: str, rec: dict):
keys = ','.join(rec.keys())
values = tuple(rec.values())
stmt = f"INSERT INTO {table_name} ({keys}) VALUES {values}"
cur.execute(stmt)

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);""")

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')

why can i insert string value into int column in python sqlite database

i run following codes in python3:
import sqlite3
conn = sqlite3.connect("data.db")
conn.execute("create table if not exists data(\
id int prinmary key,view int)")
conn.execute("insert into data (id,view) values (0,0)")
conn.execute("insert into data (id,view) values (1,'--')")
print(conn.execute("select * from data order by id").fetchall())
conn.commit()
conn.close()
and no error occured, "[(0, 0), (1, '--')]" was printed, why?
It is documented as a feature in SQLite documentation, is is even documented is its FAQ:
(3) SQLite lets me insert a string into a database column of type integer!
This is a feature, not a bug. SQLite uses dynamic typing. It does not enforce data type constraints. Data of any type can (usually) be inserted into any column...
From the sqlite page:
INSERT INTO table1 (
column1,
column2 ,..)
VALUES
(
value1,
value2 ,...);
After insert into data, you would need to tell it into which fields.

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

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.

Python database insert MySQL

I am trying to create a table in Python with MySQL, and then insert new values into the table!
The program works with no error message, but the table stays empty all the time. Here are my python scripts:
cursor = conn.cursor()
cursor.execute('DROP TABLE twitter')
cursor.execute("CREATE TABLE twitter (id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id CHAR, state CHAR(2), city CHAR, tweet CHAR, PRIMARY KEY (id))")
### after getting some data, then insert the data into the table:
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})'.format(tw_userid, tw_state, tw_city, tw_text))
cursor.close()
conn.commit()
conn.close()
But any time I try to select data from this table, I get an empty set.
I also tried without using format option, but still I get an empty set:
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', (tw_userid, tw_state, tw_city, tw_text))
Any idea why the insert command doesn;t change the table at all?
You need to use a comma to separate parameters in python.
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})'.format(tw_userid, tw_state, tw_city, tw_text))
Should be:
data = (tw_userid, tw_state, tw_city, tw_text)
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', data)
You can see the documentation for the python connector on the mysql documentation page.

Categories