sqlite3.OperationalError: table users has no column named username - python

Hello I cant figure out the solution for that problem. I searched on google but got no answer.
I'm new to db. so maybe its a dumb question :).
class Users:
def __init__(self, tablename="users", userId="userId", password="password", username="username"):
self.__tablename = tablename
self.__userId = userId
self.__password = password
self.__username = username
conn = sqlite3.connect('test.db')
print("open database successfully")
str = "CREATE TABLE IF NOT EXISTS " + tablename + "(" + self.__userId + " " + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
str += " " + self.__password + "TEXT NOT NULL ,"
str += " " + self.__username + "TEXT NOT NULL )"
conn.execute(str)
print("Table created successfully")
conn.commit()
conn.close()
def insert_user(self, username, password):
conn = sqlite3.connect('test.db')
str_insert = "INSERT INTO " + self.__tablename + " (" + self.__username +"," + self.__password + ") VALUES (" + "'" +username + "'" + "," + "'" +password +"'" +");"
print(str_insert)
conn.execute(str_insert)
conn.commit()
conn.close()
print("Record created successfully")
u = Users()
u.insert_user("yonatan#gmail.com", "123456")

Problem is here :
str = "CREATE TABLE IF NOT EXISTS " + tablename + "(" + self.__userId + " " + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
str += " " + self.__password + "TEXT NOT NULL ,"
str += " " + self.__username + "TEXT NOT NULL )"
Indeed, concatenate "username" and "TEXT NOT NULL" will give "usernameTEXT NOT NULL", without space between "username" and "TEXT"
You can see this if you execute the following query :
conn.execute("SELECT * from sqlite_master").fetchall()
This gives you :
[
('table', 'users', 'users', 2, 'CREATE TABLE users(userId INTEGER PRIMARY KEY AUTOINCREMENT , passwordTEXT NOT NULL , usernameTEXT NOT NULL )'),
('table', 'sqlite_sequence', 'sqlite_sequence', 3, 'CREATE TABLE sqlite_sequence(name,seq)')
]
Which is clearly a mess.
When you work with sqlite3, a good practice is to use the following syntax, which will avoid you a lot of space mistakes :
conn.execute(
f"CREATE TABLE IF NOT EXISTS {tablename}"
f"({self.__userId} INTEGER PRIMARY KEY AUTOINCREMENT,"
f"{self.__password} TEXT NOT NULL, {self.__username} TEXT NOT NULL)"
)

Related

How do I use a list for SQL query values?

Instead of enumerating the items in a list in this scenario:
cursor.execute("INSERT INTO " + table_name + " (url, date, " + column_headers + "total_keywords" + ")" \
"VALUES (%s,%s,%s,%s,%s,%s)",
(response.url,
datetime.date.today(),
some_list[0],
some_list[1],
some_list[2],
some_list[3],
...
some_list[n]
)
)
I would like to pass num_keywords through more generally. Is it possible to use a list in an SQL query specifically in the VALUES part of the query?
The following code snippet does not work, but this is the idea:
cursor.execute("INSERT INTO " + table_name + " (url, date, " + column_headers + "total_keywords" + ")" \
"VALUES (%s,%s,%s)",
(response.url,
datetime.date.today(),
some_list
)
)
Is this possible? How would I do it?
Use the * operator to spread the list.
cursor.execute("INSERT INTO " + table_name + " (url, date, " + column_headers + "total_keywords" + ")" \
"VALUES (%s,%s,%s,%s,%s,%s)",
(response.url, datetime.date.today(), *list)
)
BTW, don't use list as a variable name, it will replace the built-in class with that name.

Why Sqlite3 table wont UPDATE

I've tried making an update to my sqlite3 table but it doesn't seem to work.
marks = "My long name here"
conn = sqlite3.connect('mydb.db')
cur=conn.cursor()
cur.execute("UPDATE '" + str(marks) +"' SET (ENG,KIS,MAT,BIO) = (-1,-1,-1,-1) WHERE (ENG,KIS,MAT,BIO) =('nan','nan','nan','nan')")
conn.commit()
conn.close()
I can't see nay error in my code.
You don't need 4 separate statements.
You can do it in 1 statement with CASE expressions:
UPDATE tablename
SET ENG = CASE WHEN ENG = 'nan' THEN -1 ELSE ENG END,
KIS = CASE WHEN KIS = 'nan' THEN -1 ELSE KIS END,
MAT = CASE WHEN MAT = 'nan' THEN -1 ELSE MAT END,
BIO = CASE WHEN BIO = 'nan' THEN -1 ELSE BIO END
WHERE 'nan' IN (ENG,KIS,MAT,BIO)
This worked, separating them.
marks = "My long name here"
conn = sqlite3.connect('mydb.db')
cur=conn.cursor()
cur.execute("UPDATE '" + str(marks) + "' SET ENG=-1 WHERE ENG='nan'")
cur.execute("UPDATE '" + str(marks) + "' SET KIS=-1 WHERE KIS='nan'")
cur.execute("UPDATE '" + str(marks) + "' SET MAT=-1 WHERE MAT='nan'")
cur.execute("UPDATE '" + str(marks) + "' SET BIO=-1 WHERE BIO='nan'")
conn.commit()
conn.close()
Rather than this.
marks = "My long name here"
conn = sqlite3.connect('mydb.db')
cur=conn.cursor()
cur.execute("UPDATE '" + str(marks) +"' SET (ENG,KIS,MAT,BIO) = (-1,-1,-1,-1) WHERE (ENG,KIS,MAT,BIO) =('nan','nan','nan','nan')")
conn.commit()
conn.close()

How to create table dynamically in python mysql.connector?

I got an error in the 5th line in my code below at '"+uname+"'.
How can I create a table at runtime?
Here is my code :
name = en1.get()
uname = en2.get()
password = en3.get()
sql = "insert into register values ('" + name + "','" + uname + "','" + password + "')"
CreateTable = "CREATE TABLE '"+uname+"'(no INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),amount INT,date DATE,mode VARCHAR(255))"
try:
cur.execute(sql)
cur1.execute(CreateTable)
con.commit()
con1.commit()
messagebox.showinfo("Success", "Your data is registered successfully!")
except:
messagebox.showinfo("Error inserting", "Please change your username and try.")
In the statements with get(), if you get None as a return value then the below statements will fail
name = en1.get() #-- None
sql = "insert into register values ('" + name + "','" + uname + "','" + password + "')"
CreateTable = "CREATE TABLE '"+uname+"'(no INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),amount INT,date DATE,mode VARCHAR(255))"
Try this instead so that if any of the values is None, then below output will be obtained
without causing the error but still the sql query needs to be handled
sql = "insert into register values ('{}','{}','{}')".format(name, uname, password)
CreateTable = "CREATE TABLE '{}'(no INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),amount INT,date DATE,mode VARCHAR(255))".format(name)
print("sql is ", sql)
print("sql is ", CreateTable)
# Output
sql is insert into register values ('None','None','None')
sql is CREATE TABLE 'None'(no INT AUTO_INCREMENT PRIMARY KEY,title VAR
CHAR(255),amount INT,date DATE,mode VARCHAR(255))

Error : Insert Command error with Database as SQLITE

I'm inserting data into SQLite using Python
database_tasks.bookId is a class variable
def insert(self, conn,dbname, name, writer='none'):
c = conn.cursor()
if dbname == "Book_database":
database_tasks.bookId += 1
sql= "INSERT INTO Book_database VALUES(" + database_tasks.bookId + "," + name + "," + writer + ")"
else:
database_tasks.studentId += 1
sql= "INSERT INTO Student VALUES("+ database_tasks.studentId + "," + name + ")"
c.execute(sql)
conn.commit()
return None
I'm getting an error with Insert command.
sql= "INSERT INTO Book_database VALUES(" + database_tasks.bookId + "," + name + "," + writer + ")"
TypeError: can only concatenate str (not "int") to str
You should never build a query string including values to insert that way but used parameterized queries. It is an anti-pattern that has been used for decades to build SQL injection attacks. You should use:
if dbname == "Book_database":
database_tasks.bookId += 1
c.execute("INSERT INTO Book_database VALUES(?,?,?)",
(database_tasks.bookId, name, writer))
else:
...
it looks like your bookId is int. Cast it to str before combining.
sql= "INSERT INTO Book_database VALUES(" + str(database_tasks.bookId) + "," + name + "," + writer + ")"
The error is fairly self explanatory - you are trying to concatenate an integer to a string.
my assumption is that database_tasks.studentId is an int, so changing your query to
sql= "INSERT INTO Book_database VALUES(" + str(database_tasks.bookId) + "," + name + "," + writer + ")"
would fix this, however be aware that if this is public facing, it would be very easy to exploit this, I'd recommend fully validating input, or changing your approach to this problem.

Python PostgreSQL Statement Problem psycopg2 cursor.execute(Table Union)

I am new in python, and using Python & PostgreSQL (9.03) (and psycopg2 to interface between the two) in Windows XP environment.
I am working on a huge spatial dataset road network dataset, and seperating the data per Country through ArcGIS Geoprocessing, and automatically store and them in a PostGIS (1.5) Database.
While when retrieving values from the database everything works as planned:
...
try:
conn = psycopg2.connect("host = '" + HostName + "' dbname='" + DBName + "' user='" + Username + "' password='" + Password + "'")
curs = conn.cursor()
except:
print "Unable to connect to the database"
SQLStatement = "SELECT data_partition FROM datasets WHERE map_partition='" + MapPartitions[0] + "'"
curs.execute(SQLStatement)
...
When I am trying to pass the following Union Statement to Postgres, there is no resulting table, while if I take the printed SQL Statement and run it in as an SQL Statement and run it PostgresSQL, it creates the desired resulting table:
conn = psycopg2.connect("host = '" + HostName + "' dbname='" + DBName + "' user='" + Username + "' password='" + Password + "'")
cur = conn.cursor()
SQLStatement = (
"CREATE TABLE " + Schema + "." + PartitionTableName + " AS \n"
"SELECT * FROM " + Schema + "." + partName + "_Lines_" + Rel + "_Net0 UNION \n"
"SELECT * FROM " + Schema + "." + partName + "_Lines_" + Rel + "_Net1 UNION \n"
"SELECT * FROM " + Schema + "." + partName + "_Lines_" + Rel + "_Net2 UNION \n"
"SELECT * FROM " + Schema + "." + partName + "_Lines_" + Rel + "_Net3 UNION \n"
"SELECT * FROM " + Schema + "." + partName + "_Lines_" + Rel + "_Net4 UNION \n"
"SELECT * FROM " + Schema + "." + partName + "_Lines_" + Rel + "_Net5;\n"
"\n"
"\n"
"ALTER TABLE " + Schema + "." + partName + "_Lines_" + Rel + "\n"
"DROP COLUMN gid;\n"
cur.execute(SQLStatement)
conn.commit()
cur.close()
If we print the SQL Statement, this is the resulting query:
print SQLStatement
CREATE TABLE compresseddata.FRA24_Lines_2011_03 AS
SELECT * FROM compresseddata.FRA24_Lines_2011_03_Net0 UNION
SELECT * FROM compresseddata.FRA24_Lines_2011_03_Net1 UNION
SELECT * FROM compresseddata.FRA24_Lines_2011_03_Net2 UNION
SELECT * FROM compresseddata.FRA24_Lines_2011_03_Net3 UNION
SELECT * FROM compresseddata.FRA24_Lines_2011_03_Net4 UNION
SELECT * FROM compresseddata.FRA24_Lines_2011_03_Net5;
ALTER TABLE compresseddata.FRA24_Lines_2011_03
DROP COLUMN gid;
I am using variables in the to Merge different Road Network Classes, and due to different Partitions of my dataset, I need to iterate through, them, but for some reason that I cannot still understand, there is no table being produced.
Any ideas?
Thanx in advance for the help
THe SQL you are sending are actually 3 statements, not 1.
I never tried this but I expect execute to complain about this.
Additionally there is a semicolon missing in the ALTER TABLE statement.
I would recommend to add exception handling to your code and execute each SQL statement separately so you get better error reporting on what might go wrong.
Indeed Peter, this seems to be the case.
More specifically Each SQL Statement must be passed separately through:
curs.execute(SQLStatement)
and them committed via:
conn.commit()
All the changes will then be apparent in the database.
Thanx again
As already mentioned, individually executing each statement and checking the exception can provide good insight to what is occurring.
In particular psycopg2 will raise psycopg2.ProgrammingError. If the error message is not useful, you may have better luck looking up the exception's pgcode and then investigating that.
PGCodes for 9.1:
http://www.postgresql.org/docs/9.1/static/errcodes-appendix.html ).
try:
cur.execute(SQLQUERY)
except psycopg2.ProgrammingError as e:
# Err code lookup at http://www.postgresql.org/docs/9.1/static/errcodes-appendix.html
print "psycopg2 error code %s" % e.pgcode
raise e
NOTE: A cursors execute statement CAN take multiple sql statements in a single string.
ex: cur.execute('create table ABBA (); create table BETA ();') is a perfectly legitimate statement.
For this reason, do not expect cursor.execute to perform any sanity checks on a string only input!
I'd suggest (except for special rare circumstances) to execute each statement individually.

Categories