This is a very basic question and I know there are security issues with this code and it should be using parameterized entries among other issues — it is a work in progress. I am attempting to set build a user registration module for a project. I have set up a table with with the first column serving as an ID with a primary key constraint but when I run the code, I get the following error and am not sure why — (if it relates to the p_ID column):
Traceback (most recent call last):
File "user.py", line 72, in <module>
userSignUp()
File "user.py", line 68, in userSignUp
c.execute("INSERT INTO People VALUES(userName, password, confirmPassword, firstName,lastName, companyName, email, phoneNumber,addressLine1, addressLine2, addressLine3, zipCode, province, country, regDate)")
sqlite3.OperationalError: no such column: userName
The code is:
import sqlite3
import datetime
path = "/Users/workhorse/thinkful/"
db = "apartment.db"
def checkAndCreateDB():
#not checking for some reason
#fullPath = os.path.join(path, db)
#if os.path.exists(fullPath):
# print "Database Exists"
#else:
connection = sqlite3.connect(db)
print "Creating database"
createUserRegTable()
def createUserRegTable():
with sqlite3.connect(db) as connection:
c = connection.cursor()
c.execute("""CREATE TABLE People
(p_ID INTEGER PRIMARY KEY AUTOINCREMENT,
userName TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
confirmPassword TEXT NOT NULL,
firstName TEXT NOT NULL,
lastName TEXT NOT NULL,
companyName TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
phoneNumber TEXT NOT NULL,
addressLine1 TEXT NOT NULL,
addressLine2 TEXT,
addressLine3 TEXT,
zipCode TEXT NOT NULL,
province TEXT NOT NULL,
country TEXT NOT NULL,
regDate DATE NOT NULL)
""")
print "table made"
def userSignIn():
pass
def userSignUp():
userName = raw_input("Enter a user name: ")
password = raw_input("Enter a password: ")
confirmPassword = raw_input("Confirm Your Password: ")
firstName = raw_input("Enter your first name: ")
lastName = raw_input("Enter your last name: ")
companyName = raw_input("Enter your company name: ")
email = raw_input("Enter your email: ")
phoneNumber = raw_input("Enter your phone number: ")
addressLine1 = raw_input("Enter your address: ")
addressLine2 = raw_input("Enter second line of your address (Not Required): ")
addressLine3 = raw_input("Enter third line of your address (Not Required): ")
zipCode = raw_input("Enter your zip code: ")
province = raw_input("Enter your state or province: ")
country = raw_input("Enter your country: ")
regDate = datetime.date.today()
print regDate
#userInfo = (userName, password, confirmPassword, firstName,lastName, companyName, email, phoneNumber,addressLine1,
#addressLine2, addressLine3, zipCode, province, country, regDate)
with sqlite3.connect(db) as connection:
c = connection.cursor()
c.execute("INSERT INTO People VALUES(userName, password, confirmPassword, firstName,lastName, companyName, email, phoneNumber,addressLine1, addressLine2, addressLine3, zipCode, province, country, regDate)")
checkAndCreateDB()
userSignUp()
Much thanks
The sqlite3.OperationalError: no such column:
error occurs when a column name specified in the SQL query does not exist in the table. This error can be raised in a variety of circumstances, including when the table was created without the specified column or when the column was deleted from the table after the query was written. In order to resolve this error, there are several approaches that can be taken.
Method 1: Verify the column name
To fix the sqlite3.OperationalError: no such column
error, you can verify the column name in the SQL query. Here’s how to do it:
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
query = "SELECT * FROM my_table WHERE my_column = ?"
try:
c.execute(query, ('value',))
except sqlite3.OperationalError as e:
if 'no such column' in str(e):
print("Column name is incorrect")
c.close()
conn.close()
In the above code, we first connect to the SQLite database using the sqlite3.connect()
method. Then, we create a cursor using the conn.cursor()
method.
Next, we define our SQL query as a string and use a placeholder (?
) for the value we want to search for.
Before executing the query, we wrap it in a try
block and catch any OperationalError
exceptions. If the exception message contains the string 'no such column'
, we know that the column name is incorrect.
Finally, we close the cursor and the connection using the c.close()
and conn.close()
methods, respectively.
By verifying the column name in the SQL query, you can avoid the sqlite3.OperationalError: no such column
error and ensure that your queries are executed successfully.
Method 2: Add the missing column
To fix the sqlite3.OperationalError: no such column
error, you can add the missing column to your SQLite table using the ALTER TABLE
statement. Here is the step-by-step guide to do it:
- Connect to your SQLite database using the
connect()
method from thesqlite3
module:
import sqlite3
conn = sqlite3.connect('your_database.db')
- Create a cursor object using the
cursor()
method:
- Check the column names of your table using the
PRAGMA table_info()
statement:
cursor.execute("PRAGMA table_info(your_table)")
columns = [column[1] for column in cursor.fetchall()]
print(columns)
- If the missing column is not in the list of columns, add it using the
ALTER TABLE
statement:
if 'missing_column' not in columns:
cursor.execute("ALTER TABLE your_table ADD COLUMN missing_column TEXT")
print("Missing column added.")
- Commit the changes using the
commit()
method:
- Close the cursor and the connection:
cursor.close()
conn.close()
Here is the complete code example:
import sqlite3
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()
cursor.execute("PRAGMA table_info(your_table)")
columns = [column[1] for column in cursor.fetchall()]
print(columns)
if 'missing_column' not in columns:
cursor.execute("ALTER TABLE your_table ADD COLUMN missing_column TEXT")
print("Missing column added.")
conn.commit()
cursor.close()
conn.close()
This code will add the missing column to your SQLite table and solve the sqlite3.OperationalError: no such column
error.
Method 3: Use the ALTER TABLE statement to add the missing column
To fix the sqlite3.OperationalError: no such column
error in Python, you can use the ALTER TABLE
statement to add the missing column. Here are the steps to do it:
- Connect to the SQLite database using the
connect()
method from thesqlite3
module:
import sqlite3
conn = sqlite3.connect('database.db')
- Create a cursor object using the
cursor()
method:
- Use the
ALTER TABLE
statement to add the missing column to the table:
cursor.execute("ALTER TABLE table_name ADD COLUMN column_name datatype")
Replace table_name
, column_name
, and datatype
with the appropriate values for your table and column.
- Commit the changes using the
commit()
method:
Here’s an example code snippet that demonstrates how to add a missing column named email
to a table named users
with a TEXT
data type:
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
cursor.execute("ALTER TABLE users ADD COLUMN email TEXT")
conn.commit()
This code will add the email
column to the users
table in the database.db
SQLite database.
Method 4: Modify the query to reference a different column
To fix the error «sqlite3.OperationalError: no such column» in Python, you can modify the query to reference a different column. Here are the steps to do it:
- Open your SQLite database using Python:
import sqlite3
conn = sqlite3.connect('your_database.db')
- Create a cursor object:
- Modify the query to reference a different column. For example, if you have a table called «users» and you want to select the «name» column, but you get the error «no such column: name», you can modify the query to select a different column, like «id»:
query = "SELECT id FROM users"
- Execute the query using the cursor:
- Fetch the results:
results = cursor.fetchall()
- Close the cursor and the connection:
cursor.close()
conn.close()
Here’s the complete code example:
import sqlite3
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()
query = "SELECT id FROM users"
cursor.execute(query)
results = cursor.fetchall()
cursor.close()
conn.close()
That’s it! By modifying the query to reference a different column, you can fix the «no such column» error in SQLite.
I have a table (trackedinfo
) inside my database that has the following columns (columns obtained by running PRAGMA table_info(trackedinfo);
)
The problem is that even though the column sendok
exists, when running a query on the database with that field, it throws an error.
Example queries:
SELECT * FROM trackedinfo WHERE sendok IS NULL;
SELECT sendok FROM trackedinfo;
Error:
SQLITE_ERROR: SQL error or missing database (no such column: sendok)
But, if I run a query selecting all of the fields, it brings me the info regarding sendok
:
Here is the CREATE
command of the database:
CREATE TABLE trackedinfo
(
id INTEGER PRIMARY KEY,
date_time_start TEXT,
date_time_end TEXT,
tracked_name TEXT,
tracked_origin TEXT,
tracked_maker TEXT,
tracked_version TEXT,
tracked_type TEXT,
sendok TEXT,
tracked_id TEXT
);
It also happens with the column tracked_id
Info that I got by executing .schema trackedinfo
CREATE TABLE IF NOT EXISTS "trackedinfo" ("id" INTEGER PRIMARY KEY, "date_time_start" TEXT, "date_time_end" TEXT, "tracked_name" TEXT, "tracked_origin" TEXT, "tracked_maker" TEXT, "tracked_version" TEXT, "tracked_type" TEXT, "sendok " TEXT, "tracked_id " TEXT);
-
#1
from sqlite3 import *
base = connect(«BASE.db»)
cursor = base.cursor()
LIST10 = list(cursor.execute(«»»SELECT Номер10 FROM Words»»»))
LIST11 = list(cursor.execute(«»»SELECT Номер11 FROM Words»»»))
LIST12 = list(cursor.execute(«»»SELECT Номер12 FROM Words»»»))
LIST15 = list(cursor.execute(«»»SELECT Номер15 FROM Words»»»))
cursor.execute(«»»DELETE FROM Words»»»)
def write_funck(list_num,num):
INP = None
while INP != »:
INP = input(‘Введите слово для номера 10: ‘)
list_num.append(INP.lower())
list_num.remove(»)
word_set = set(list_num)
list_num = list(word_set)
def main():
choose = int(input(‘выберете номер задания(10,11,12,15): ‘))
if choose == 10:
write_funck(LIST10,choose)
elif choose == 11:
write_funck(LIST11,choose)
elif choose == 12:
write_funck(LIST12,choose)
else:
write_funck(LIST15,choose)
main()
cursor.execute(f»»»INSERT INTO Words(Номер10) VALUES({LIST10})»»»)
cursor.execute(f»»»INSERT INTO Words(Номер11) VALUES({LIST11})»»»)
cursor.execute(f»»»INSERT INTO Words(Номер12) VALUES({LIST12})»»»)
cursor.execute(f»»»INSERT INTO Words(Номер15) VALUES({LIST15})»»»)
base.commit()
cursor.close()
0
-
#3
sqlite3(No such column(Элементы массива)) — это значит что в таблице нет такого столбца.
Вот тут есть пример вставки данных в таблицу:
https://younglinux.info/sqlite/insert
Так проблема в том,что я добавляю в столбец(Номер10) массив состоящий из слов.Но в качестве столбцов программа использует элементы массива, и я не понимаю почему.Вроде по синтаксису Insert сделан правильно.
0
-
#4
По коду не понятно какие столбцы у вас в таблице (сколько их и какого они типа). Покажите код которым создаете таблицу.
0
-
#5
По коду не понятно какие столбцы у вас в таблице (сколько их и какого они типа). Покажите код которым создаете таблицу.
0
-
#6
Список в базу можно добавить в виде строки (т. к. в виде списка не примет):
Python:
from sqlite3 import *
base = connect('BASE.db')
cursor = base.cursor()
l = ['1', '2', '3']
cursor.execute("""INSERT INTO Words ('Номер10') VALUES (?)""", (str(l),))
base.commit()
base.close()
0
-
#7
Или можно список объединить в строку с помощью join и записать, а при получении разделять через split:
Запись:
Python:
from sqlite3 import *
base = connect('BASE.db')
cursor = base.cursor()
l = ['1', '2', '3']
x = ",".join(l)
cursor.execute("""INSERT INTO Words ('Номер10') VALUES (?) """, (x,))
base.commit()
base.close()
Чтение:
Python:
from sqlite3 import *
base = connect('BASE.db')
cursor = base.cursor()
c = cursor.execute("""SELECT Номер10 FROM Words WHERE rowid=1""")
l = c.fetchone()
y = l[0].split(',')
print(y)
Запись в определенный ряд таблицы:
Python:
base = connect('BASE.db')
cursor = base.cursor()
l = ['1', '2', '3']
x = ",".join(l)
cursor.execute("""UPDATE Words SET 'Номер10' = (?) WHERE rowid=1""", (x,))
base.commit()
base.close()
0
-
#8
Список в базу можно добавить в виде строки (т. к. в виде списка не примет):
Python:
from sqlite3 import * base = connect('BASE.db') cursor = base.cursor() l = ['1', '2', '3'] cursor.execute("""INSERT INTO Words ('Номер10') VALUES (?)""", (str(l),)) base.commit() base.close()
Спасибо вам огромное)))))
When I run the following query, SQLite tells me that there is no such column «test», where «test» is the value in the variable $entryname. I want to store $entryname into the name column, not ‘name’ into $entryname. Does anyone know how to do this?
$query = 'INSERT INTO files (name, description, filename) VALUES (' . $entryname . ', ' . $entrydescription . ', ' . $filename . ')';
asked Apr 8, 2011 at 0:43
You need to quote your string values. They are getting interpreted as a SQLite variable otherwise.
Try the following:
$query = "INSERT INTO files (name, description, filename) VALUES ('" . $entryname . "', '" . $entrydescription . "', '" . $filename . "')";
You should also look into preventing SQL Injection.
answered Apr 8, 2011 at 0:45
Jason McCrearyJason McCreary
71.6k23 gold badges135 silver badges174 bronze badges
0