I am creating a test script to create database and insert data.
database is created but no table is creating.
here is code.
import sqlite3
def connect() :
conn=sqlite3.connect("fullsta.db" )
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS post(id INTEGER PRIMARY KEY,title text,content text,date text,author text)")
conn.commit()
conn.close()
def insert(title,content,date,author):
conn=sqlite3.connect("fullsta.db" )
cur=conn.cursor()
cur.execute("INSERT INTO post VALUES (NULL,title ,content ,date,author )")
conn.commit()
conn.close()
insert("hello","hello","hello","hello")
here is the error.
PS C:\Users\Anil Kumar\Desktop\project\my site\web_blog> py test.py
Traceback (most recent call last):
File "test.py", line 17, in <module>
insert("hello","hello","hello","hello")
File "test.py", line 13, in insert
cur.execute("INSERT INTO post VALUES (NULL,title ,content ,date,author )")
sqlite3.OperationalError: no such table: post
Your code does not have connect function called.
but you need more clearer code to see what is happening.
maybe this will handle what you want to do
import sqlite3
class DB:
cursor = None
connection = None
def __init__(self, db):
connection = sqlite3.connect(db)
self.cursor = connection.cursor()
self.connection = connection
def migrate(self):
q = "CREATE TABLE IF NOT EXISTS post(id INTEGER PRIMARY KEY,title text,content text,date text,author text)"
self.cursor.execute(q)
def exec(self, sql, variables=None):
if variables:
return self.cursor.execute(sql, variables).fetchall()
return self.cursor.execute(sql).fetchall()
def commit(self):
self.connection.commit()
def close(self):
self.connection.close()
def force_exit(self):
self.commit()
self.close()
def insert(title, content, date, author):
cur = DB("fullsta.db")
cur.migrate()
cur.exec("INSERT INTO post VALUES (NULL, ?, ?, ?, ? )", (title, content, date, author))
cur.force_exit()
insert("hello", "hello", "hello", "hello")
Related
I tried to create table in my database and add PRIMARY KEY to my table by using sqlite3 library, But sqlite3 did not understand NULL
this my code:
import sqlite3
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)")
conn.commit()
conn.close()
def insert(title,author,year,isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title,author,year,isbn))
conn.commit()
conn.close()
view()
def view():
conn=sqlite3.connect('books.db')
cur=conn.cursor()
cur.execute("SELECT \* FROM book")
rows=cur.fetchall()
conn.close()
return rows
connect()
insert('anybook','anyperson',1918,6384515345)
print(view())
I expected the output to be
[(1,'anybook','anyperson',1918,6384515345)]
But it was:
Traceback (most recent call last):
File "e:\CORSES\The Python Mega Course\000. Projects\APPs\4. BookStore\Book Store\BackEnd.py", line 28, in <module>
insert('anybook','anyperson',1918,6384515345)
File "e:\CORSES\The Python Mega Course\000. Projects\APPs\4. BookStore\Book Store\BackEnd.py", line 13, in insert
cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title,author,year,isbn))
sqlite3.OperationalError: table book has 4 columns but 5 values were supplied
Why is my program giving me error indicating that that column does not exist in my Sqlite3 Tasks-table? Here is my code:
class Db:
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
def create_table(self):
create_Tasks_table = '''CREATE TABLE Tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
notes TEXT,
deadline TEXT,
state INTEGER);'''
self.cursor.execute(create_Tasks_table)
self.conn.commit()
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = """INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?), (title, notes, deadline, state)"""
self.cursor.execute(add_to_Tasks_table)
self.conn.commit()
if __name__ == "__main__":
db = Db()
db.create_table()
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
I checked with DB Browser for SQlite that table is created correctly and column name is correct, as indicated on this picture:
EDIT: Here is full error:
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\project\mytest.py", line 91, in <module>
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
File "C:\Users\User\PycharmProjects\project\mytest.py", line 36, in add_task
self.cursor.execute(add_to_Tasks_table)
sqlite3.OperationalError: no such column: title
The problem with your code is that you included the tuple that contains the parameters that you pass inside the sql statement.
It should be placed as the 2nd argument of cursor.execute():
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = "INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?)"
self.cursor.execute(add_to_Tasks_table, (title, notes, deadline, state))
self.conn.commit()
I wanna make a temporary database but I don't know I going in the right way or not
I get the error no such table: list but I don't know why python raise that error
this is my code:
def connect():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS list (id INTEGER PRIMARY KEY , namee VARCHAR , number INTEGER ,"
" price INTEGER )"
)
conn.commit()
conn.close()
def insert(name, number, price):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"INSERT INTO list VALUES (NULL ,?,?,?,?,?)", (name, number, price)
)
conn.commit()
conn.close()
def view():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"SELECT * FROM list"
)
rows = cur.fetchall()
conn.close()
return rows
def delete(id):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("DELETE FROM list WHERE id=?", (id,))
conn.commit()
conn.close()
connect()
and this is my error:
Traceback (most recent call last):
File "D:\python\WindowsProject\app\user\memory.py", line 42, in <module>
print(insert('pizza',2,6))
File "D:\python\WindowsProject\app\user\memory.py", line 17, in insert
cur.execute(
sqlite3.OperationalError: no such table: list
sqlite3.connect(":memory:") creates an in-memory database that only exists as long as the connection is in use.
The problem is that you're closing the database connection in each function. As soon as you close it, the in-memory database vanishes. INSERT fails because the table no longer exists.
You'll need to preserve (or pass) the conn and cur objects so that you can use them between functions.
On the web I found this illustration to create a database with gui with Tkinter. Everything ok, except when I enter the data and click on the Add button. I'm getting:
NameError: name 'db' is not defined
I think what I am wrong is nonsense in this part of the code. What am I doing wrong?
Here is my code uploaded su un editor online. I am writing it here because it is too long to enter. I am new and having difficulty with StackOverflow. If we can figure out the error, I'll update the question with the code I'm wrong.
import sqlite3
conn = sqlite3.connect('/home/dekstop/db.db')
cur = conn.cursor()
class Database:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
self.cur.execute(
"CREATE TABLE IF NOT EXISTS routers (id INTEGER PRIMARY KEY, hostname text, brand text, ram integer, flash integer)")
self.conn.commit()
def fetch(self, hostname=''):
self.cur.execute(
"SELECT * FROM routers WHERE hostname LIKE ?", ('%'+hostname+'%',))
rows = self.cur.fetchall()
return rows
def fetch2(self, query):
self.cur.execute(query)
rows = self.cur.fetchall()
return rows
def insert(self, hostname, brand, ram, flash):
self.cur.execute("INSERT INTO routers VALUES (NULL, ?, ?, ?, ?)",
(hostname, brand, ram, flash))
self.conn.commit()
def remove(self, id):
self.cur.execute("DELETE FROM routers WHERE id=?", (id,))
self.conn.commit()
def update(self, id, hostname, brand, ram, flash):
self.cur.execute("UPDATE routers SET hostname = ?, brand = ?, ram = ?, flash = ? WHERE id = ?",
(hostname, brand, ram, flash, id))
self.conn.commit()
def __del__(self):
self.conn.close()
You have this:
import sqlite3
conn = sqlite3.connect('/home/dekstop/db.db')
cur = conn.cursor()
class Database:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
self.cur.execute(
"CREATE TABLE IF NOT EXISTS routers (id INTEGER PRIMARY KEY, hostname text, brand text, ram integer, flash integer)")
self.conn.commit()
...
Right away, you can see a problem there. You have conn and curr defined outside the class and inside. It seems clear that the rest of your code expects db to be an instance of the Database class. So you need:
import sqlite3
class Database:
... same as always ...
db = Database('/home/dekstop/db.db')
and you need to do that before any of the code that refers to db.
assigned variable DB not defined. so it raises an error
def add_router():
if brand_text.get() == '' or hostname_text.get() == '' or ram_text.get() == '' or flash_text.get() == '':
messagebox.showerror('Required Fields', 'Please include all fields')
return
db.insert(hostname_text.get(), brand_text.get(),
ram_text.get(), flash_text.get())
clear_text()
populate_list()
I get the following error when I run my code and I don't know why:
Traceback (most recent call last):
File "python", line 27, in <module>
File "python", line 25, in members_of_circles
sqlite3.OperationalError: no such column: circleCat.name
the code :
import sqlite3
con = sqlite3.connect(":memrory:")
cur = con.cursor()
def creat_tables () :
cur.execute("CREATE table circleCat (id INTEGER PRIMARY KEY, name TEXT,
description TEXT)")
cur.execute("CREATE table members( id INTEGER PRIMARY KEY, name TEXT, level
TEXT, crcl TEXT)")
def add_a_member(name, level, crcl):
cur.execute("INSERT INTO members (name, level, crcl) VALUES (?, ?, ?)" ,
(name, level, crcl));
def add_a_circle(name, description):
cur.execute("INSERT INTO circleCat (name, description) VALUES (?, ?)" ,
(name, description));
creat_tables ()
add_a_circle("Gaming", "for Gaming")
add_a_member("hossam", "beginner", "Gaming")
def members_of_circles():
cur.execute("SELECT name FROM members WHERE members.crcl =
circleCat.name")
members_of_circles()
Your select query is wrong. Try this:
def members_of_circles():
cur.execute("SELECT m.name FROM members m, circleCat c WHERE m.crcl = c.name")