sqlite3.OperationalError: no such table: kupuvac - python

I need to make two tables for SQLite database, when I try to insert data to the first table, it works without any error, but when I try to insert data for the second table it gives me error: sqlite3.OperationalError: no such table: kupuvac
This code for the first table:
db=sqlite3.connect("magacin")
cursor = db.cursor()
cursor.execute('''
CREATE TABLE magacin(id INTEGER PRIMARY KEY, model TEXT,
proizvoditel TEXT, cena FLOAT , kolicina INTEGER)
''')
The code for the second table(the one that gives the error)
db=sqlite3.connect("kupuvac")
cursor = db.cursor()
cursor.execute('''
CREATE TABLE artikli(id INTEGER PRIMARY KEY,
ime_prezime TEXT, ulica TEXT, kontakt TEXT)
''')
Here`s the full traceback:
Traceback (most recent call last):
File "C:\Users\Nenad\Desktop\Magacin1\1.py", line 8, in <module>
cur.execute('''INSERT INTO kupuvac(ime_prezime, ulica, broj) VALUES(?,?,?)''',(ime, ulica,broj))
sqlite3.OperationalError: no such table: kupuvac
Can anyone please tell me what`s wrong and why it gives me an error?

You haven't supplied code that performs insertion but from what I see in the error I can assume that you passed invalid values for the table name and column names.
Database is "kupuvac" and the table name is "artikli" but you want to insert data into "kupuvac" table which does not exist.

Related

sqlite3.DatabaseError: malformed database schema (?)

I executed the python file in the first try & it worked. But when I included the code "IF NOT EXISTS" in the line cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")& cur.execute("INSERT INTO store VALUES ('Wine Glass,8,10.5')") I am getting an error.
here is my code:
import sqlite3
conn=sqlite3.connect("lite.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
cur.execute("INSERT INTO store VALUES ('Wine Glass,8,10.5')")
conn.commit()
conn.close()
here is the error:
PS D:\mysite\Interacting with Databases> python 1.py
Traceback (most recent call last):
File "D:\mysite\Interacting with Databases\1.py", line 5, in <module>
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
sqlite3.DatabaseError: malformed database schema (?)
You have an error in the code:
cur.execute("INSERT INTO store VALUES ('Wine Glass,8,10.5')")
You are providing only single value to three-column table. Replace it with:
cur.execute("INSERT INTO store VALUES ('Wine Glass','8','10.5')")
and your code should work fine.

sqlite3.OperationalError: no such table: timetable

I'm missing a table called 'timetable'.
Traceback (most recent call last):
File "C:\Users\samsshow\Desktop\microsoft-teams-class-attender-main\bot.py", line 265, in <module>
add_timetable()
File "C:\Users\samsshow\Desktop\microsoft-teams-class-attender-main\bot.py", line 108, in add_timetable
c.execute("INSERT INTO timetable VALUES ('%s','%s','%s','%s')"%(name,start_time,end_time,day))
sqlite3.OperationalError: no such table: timetable
Did you create the table? If not:
CREATE TABLE timetable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255), start_time DATETIME, end_time DATETIME, day DATE);
If you already did, maybe you misspelled your table name.
You don't have the table timetable in your database, but you probably already figured this out.
It's impossible to say anything else based on the information you provided. What are you trying to do? What have you tried? Error log is not enough.

PostgreSQL: Unable to drop a specific table named "user"

I'm unable to delete a specific table in my PostgreSQL database. That table is called "user". When I try to run the snippet of code below,
import psycopg2
conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
cur = conn.cursor()
cur.execute("DROP TABLE user;")
conn.commit()
conn.close()
It spits out the following error
Traceback (most recent call last):
File "dev_psycog.py", line 20, in <module>
cur.execute("DROP TABLE user;")
psycopg2.ProgrammingError: syntax error at or near "user"
LINE 1: DROP TABLE user;
I can delete any other table in my database just fine, but I can't seem to delete my table called "user". Is it because "user" is a reserved keyword?
Quote "user" as below
import psycopg2
conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'")
cur = conn.cursor()
cur.execute('DROP TABLE "user";')
conn.commit()
conn.close()
See here.
There is a second kind of identifier: the delimited identifier or
quoted identifier. It is formed by enclosing an arbitrary sequence of
characters in double-quotes (").

How to insert a table consist of several dictionaries into MySQL tables?

I have the below result from my python code:
[
{filename:'1,2',Name:'Gorge',registration number: '6657', registration date: '2012-09-10 14:31:13'},
{filename:'5,43',Name:'mazu',registration number:'45', registration date:'2012-10-08 17:28:47'}]
and as soon as I want to put it in a MySQL table, I got this error:
Traceback (most recent call last):
File "C:\Users\jio\Datasets 1\MyTable_info.py", line 63, in <module>
cur.executemany(query,records)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 243, in executemany
self.errorhandler(self, ProgrammingError, msg.args[0])
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: not enough arguments for format string
My python code to insert the result in MySQL table is the below code:
con = MySQLdb.connect(host = "******", port=***, user = "***", passwd="*****", db="****")
with con:
cur=con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS info(id INT(10) auto_increment primary key,file_name VARCHAR(10),
Name VARCHAR(50),Registration ID INT(50),registration time INT(50))''')
query= "INSERT INTO info (file_name, Name, Registration ID, registration time) VALUES ( %s, %s, %s, %s )"
cur.executemany(query,records)
con.commit()
Does anyone has an idea why I get this error and what does the error mean?
You are trying to insert a String into a field INT(50).
Take a look in the last field of the table, registration time field. It is an Integer and you are trying to insert values like '2012-10-08 17:28:47' or '2012-09-10 14:31:13'.
For a quick fix just change registration time field type as a VARCHAR(50).
But maybe, for perfomance issues, you should think to use some kind of TIMESTAMP field instead of a VARCHAR for this kind of purposes.
Apart from don't use INT type for field where you would like to add some kind of String.
Modify the records variable from
[ {filename:'1,2',Name:'Gorge',registration number: '6657', registration date: '2012-09-10 14:31:13'},
{filename:'5,43',Name:'mazu',registration number:'45', registration date:'2012-10-08 17:28:47'}]
to
[('1,2','Gorge','6657', '2012-09-10 14:31:13'),('5,43','mazu','45','2012-10-08 17:28:47')]
And avoid use whitespaces for the columns names as well
Try to quote field names. What the contents of records?
Don't use spaces in field names.
If you are required to, quote them with the ` character.

python inserting single quotes (') around MySQL table name

I have a database called project1 with the following tables:
_systbl1
_systbl2
_systbl3
dataset1
dataset2
dataset3
MySQL user odbc will need to be granted SELECT permissions on dataset% tables whenever a new one is added.
To accomplish this, I'm using a simple python script, like so:
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(
host="localhost",
user="user",
passwd="pass",
db="project1"
)
# Create Cursor Object
cur = db.cursor()
# get list of tables beginning with dataset
cur.execute("SHOW TABLES FROM project1 LIKE 'dataset%';")
# run GRANT statement for each table
for row in cur.fetchall() :
cur.execute("GRANT SELECT ON `project1`.`%s` TO `odbc`#`localhost`;", row)
cur.execute("GRANT SELECT ON `project1`.`%s` TO `odbc`#`%`;", row)
Unfortunately, it gives me the following error:
Traceback (most recent call last):
File "mysql_query.py", line 20, in <module>
cur.execute("GRANT SELECT ON `project1`.`%s` TO `odbc`#`localhost`;", row)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1146, "Table 'project1.'dataset1'' doesn't exist")
As you can see in the last line of the error, the problem is that python is putting a single quote around the table names when generating the query.
What am I missing here?
Do not use SQL parameters for table names. SQL parameters are escaped by the database adapter to not be interpreted as anything but literal values.
You'll have to interpolate those yourself instead, but be absolutely certain that your table name does not hold untrusted data (prevent SQL injection attacks):
cur.execute("GRANT SELECT ON `project1`.`%s` TO `odbc`#`localhost`;" % row)
cur.execute("GRANT SELECT ON `project1`.`%s` TO `odbc`#`%%`;" % row)
(where the % character in the grant has been escaped by doubling it to %%).
Instead use:
cur.execute("GRANT SELECT ON `project`.`%s` TO `odbc`#`localhost`" % row)
This will not use the normal escaping of the input. Beware of a backtick in any of your table names, though.
sql = """CREATE TABLE IF NOT EXISTS `""" + project + """` ( `id` INT(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`))"""

Categories

Resources