Sqlite ошибка no such table

I am trying to store data about pupils at a school. I’ve done a few tables before, such as one for passwords and Teachers which I will later bring together in one program.

I have pretty much copied the create table function from one of these and changed the values to for the Pupil’s information. It works fine on the other programs but I keep getting:

sqlite3.OperationalError: no such table: PupilPremiumTable

when I try to add a pupil to the table, it occurs on the line:

cursor.execute("select MAX(RecordID) from PupilPremiumTable")

I look in the folder and there is a file called PupilPremiumTable.db and the table has already been created before, so I don’t know why it isn’t working.

Here is some of my code, if you need more feel free to tell me so, as I said it worked before so I have no clue why it isn’t working or even what isn’t working:

with sqlite3.connect("PupilPremiumTable.db") as db:
    cursor = db.cursor()
    cursor.execute("select MAX(RecordID) from PupilPremiumTable")
    Value = cursor.fetchone()
    Value = str('.'.join(str(x) for x in Value))
    if Value == "None":
        Value = int(0)
    else:
        Value = int('.'.join(str(x) for x in Value))
    if Value == 'None,':
        Value = 0
    TeacherID = Value + 1
    print("This RecordID is: ",RecordID)

The sqlite3.OperationalError: no such table error occurs when trying to execute a SQL statement that refers to a table that does not exist in the specified database. It is a common issue faced by developers who use SQLite as their database management system. This error can be resolved by checking the spelling and case sensitivity of the table name, verifying that the table exists in the correct database, or by creating the missing table in the database.

Method 1: Check the spelling and case sensitivity of the table name

If you are encountering the sqlite3.OperationalError: no such table: error message in Python, it is likely that the table name you are referencing does not exist in your SQLite database. One possible solution is to check the spelling and case sensitivity of the table name.

Here’s an example code snippet that demonstrates how to check the spelling and case sensitivity of the table name in Python:

import sqlite3

conn = sqlite3.connect('example.db')

cursor = conn.cursor()

table_name = 'my_table'

cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table_name,))
result = cursor.fetchone()

if result is not None:
    print(f"The '{table_name}' table exists in the database.")
else:
    print(f"The '{table_name}' table does not exist in the database.")

In this example, we first connect to the SQLite database using the sqlite3.connect() function. Then, we create a cursor object using the conn.cursor() method. Next, we define the table name we want to check and execute a SELECT statement to retrieve the name of all tables in the database that match the given name. We use a parameterized query to prevent SQL injection attacks.

The cursor.fetchone() method retrieves the first row of the result set returned by the SELECT statement. If the table exists, the result variable will contain the name of the table. We then check if result is not None and print a message indicating whether the table exists or not.

By checking the spelling and case sensitivity of the table name, you can avoid the sqlite3.OperationalError: no such table: error message in Python.

Method 2: Verify that the table exists in the correct database

To verify that the table exists in the correct database, you can use the following code:

import sqlite3

conn = sqlite3.connect('database.db')

cursor = conn.cursor()

table_name = 'example_table'

cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'")
table_exists = cursor.fetchone()

if table_exists:
    print(f"The table '{table_name}' exists in the database.")
else:
    print(f"The table '{table_name}' does not exist in the database.")

In this code, we first connect to the database using sqlite3.connect(). We then create a cursor object using conn.cursor(), which allows us to execute SQL commands on the database.

Next, we define the name of the table we want to check for existence using table_name.

We then execute a SELECT statement on the sqlite_master table, which is a system table that contains information about all of the tables in the database. We check if there is a table with the name table_name by using a WHERE clause that filters for tables with a name column equal to table_name. We also filter for tables with a type column equal to 'table', which ensures that we only look for actual tables and not other types of objects in the database.

We then use cursor.fetchone() to retrieve the first row of the result set, which will either be None if there is no table with the specified name, or a tuple containing the name of the table if it does exist.

Finally, we check if table_exists is not None, which indicates that the table exists in the database. If it does, we print a success message. Otherwise, we print a failure message.

This method allows you to quickly check if a table exists in a database, which can help you diagnose errors like the sqlite3.OperationalError: no such table error.

Method 3: Create the missing table in the database

To fix the Python sqlite3.OperationalError: no such table error, you can create the missing table in the database. Here are the steps to do this:

  1. Connect to the database using the connect() method from the sqlite3 module:
import sqlite3

conn = sqlite3.connect('database.db')
  1. Create a cursor object using the cursor() method:
  1. Check if the table exists in the database using the execute() method with a SELECT statement and the fetchone() method. If the table does not exist, create it using the execute() method with a CREATE TABLE statement:
cursor.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';''')
if cursor.fetchone() is None:
    cursor.execute('''CREATE TABLE table_name (column1 datatype, column2 datatype, column3 datatype);''')
  1. Commit the changes using the commit() method:
  1. Close the cursor and the connection using the close() method:
cursor.close()
conn.close()

Here is the complete code:

import sqlite3

conn = sqlite3.connect('database.db')
cursor = conn.cursor()

cursor.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';''')
if cursor.fetchone() is None:
    cursor.execute('''CREATE TABLE table_name (column1 datatype, column2 datatype, column3 datatype);''')

conn.commit()

cursor.close()
conn.close()

This code will create the table_name table with three columns (column1, column2, column3) if it does not exist in the database.db database.

Пишу систему регистрации для ТГ бота, создал базу данных, все что нужно написал и запускаю и ошибка sqlite3.OperationalError: no such table: users
Код, где класс для базы данных: (оттуда ошибка)

import sqlite3
conn = sqlite3.connect('database.db')
class Database:
    def __init__(self, db_file):
        self.connection = sqlite3.connect(db_file)
        self.cursor = self.connection.cursor()
    
    def add_user(self, user_id):
        with self.connection:
           return self.cursor.execute("INSERT INTO 'users' ('user_id') VALUES (?)", (user_id,))
    
    def user_exists(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT * FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchall()
            return bool(len(result))

    def set_nicname(self, user_id, nickname):
         with self.connection:
            return self.cursor.execute("UPDATE 'users' 'SET' 'nickname' = ? WHERE 'user_id' = ?", (nickname, user_id,))

    def get_signup(self, user_id):
        with self.connection:
            result = self.cursor.execute("SELECT 'signup' FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchall()
            for row in result:
                signup = str(row(0))
            return signup

    def set_signup(self, user_id, signup):
         with self.connection:
            return self.cursor.execute("UPDATE 'users' 'SET' 'signup' = ? WHERE 'user_id' = ?", (signup, user_id,))

И ошибка раздаётся из 14-той строчки кода — вот она

result = self.cursor.execute("SELECT * FROM 'users' WHERE 'user_id' = ?", (user_id,)).fetchall()
            return bool(len(result))

Если надо, то вот скрин базы данных и таблицы:
62b30f073f29a366949822.jpeg
Не пойму: В чём ошибка, если таблица существует…
Подскажите, кто знает.

Sqlite and Python Error – sqlite3.OperationalError: no such table is an error which occurs when the directory of your database is different than your working directory.

Today I will be explaining why this error is taking place and how to solve it.

This is an error which occurs when the directory of your database is different than your working directory.

Beware of mixing between different errors. Please make sure you are dealing with the same error.

                                                                       #
sqlite3.OperationalError: no such table: <yourTable>
                                                                       #

Bellow is a number of tested solutions that I have tried and worked for me.

The Method that eliminated my problem : Correctly get the directory where the database lives

The error occurs when the directory of the database is not the same as the directory of your scripts.

It gets confusing yes, since this is most likely a new database and you do not know it is path. Do not worry the fix is simple, you can just derive the path of your database from the path of your working directory.

This is how your code is going to look like.

First, you should start by importing os.path. using the line of code bellow.

                                                                       #
import os.path
                                                                       #

Store the path of the directory in DIRorigin for example

                                                                       #
DIRorigin = os.path.dirname(os.path.abspath(__file__))
                                                                       #

Now, we should use the line of code bellow to store the path to the database in DBpath

                                                                       #
DBpath = os.path.join(BASE_DIR, "mydatabase.db")
                                                                       #

and Voila, do not forget to add this line at the end.

                                                                       #
with sqlite3.connect(DBpath) as db:
                                                                       #

This method should fix the issue for most people, If that is not the case for you, I am sorry but I do not know any other way to solve this issue. The only method that solved my problem is the method above.

I hope this guide solved your problem, thank you for reading. Goof luck with your Python Journey.

Summing-up : 

This is the end of this article guys, I hope one of these solutions worked for you depending on which OS you have, I wish you good luck with your Python Journey. For donations you can use the red Kofi button above.

Thank you for reading, keep coding and cheers. If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/

@devanp92

I’m getting the following error:

in serialize
err:  { [Error: SQLITE_ERROR: no such table: temp] errno: 1, code: 'SQLITE_ERROR' }
/home/project/node_modules/sqlite3/lib/trace.js:28
                    throw err;
                          ^
Error: SQLITE_ERROR: no such table: temp
    at Error (native)
--> in Database#each('select * from temp', [Function])

temp.db is in the same folder, so there shouldn’t be any pathing issue.

Setup:

  • node v0.12.2
  • npm v2.7.5
  • node-sqlite3 v.3.0.5
  • OSX Yosemite

I am writing the querying logic in my Sails controller. Just testing it out with a simple «SELECT * FROM TEMP» statement. Here is my source code:

var sqlite = require('sqlite3').verbose()
var db = new sqlite.Database('temp.db')

module.exports = {
  search: function(next) {
    db.serialize(function(){
            db.all('SELECT * FROM TEMP', function(err, rows) {
                if(err) {
                    console.log("err: ", err)
                    throw err
                }
                rows.forEach(function (row) {
                    console.log(row)
                })
                closeDb()
                next(err, rows)
            })
        })
    }
}

function closeDb(rows) {
    console.log("closeDb")
    db.close()
}

I feel like the reason is due to asynchro call to DB, however, I am using serializable to thwart that.

@talkingtab

Opening a table in node-sqlite3 is such a fundamental thing that the
first thought would be the database is not what you expect, for example
that the database temp.db does not contain a table «temp» or a similar
error.

You can use sqlite3 from the command line to open the database and then
to check the table.

sqlite3 temp.db
.tables
.schema

If the db has the table «temp» then you would need to provide more
information (like the result of the .tables command), a full code
listing perhaps one that shows the creation of the table as well
insertion of data and then a select.

On 4/21/15 12:00 PM, Devan Patel wrote:

I’m getting the following error:

in serialize
err: { [Error: SQLITE_ERROR: no such table: temp] errno: 1, code: ‘SQLITE_ERROR’ }
/home/node_modules/sqlite3/lib/trace.js:28
throw err;
^
Error: SQLITE_ERROR: no such table: temp
at Error (native)
—> in Database#each(‘select * from temp’, [Function])

Setup:

  • node v0.12.2
  • npm v2.7.5
  • node-sqlite3 v.3.0.5
  • OSX Yosemite

I am writing the querying logic in my Sails controller. Just testing it out with a simple «SELECT * FROM TEMP» statement. Here is my source code:

var sqlite = require(‘sqlite3’).verbose()
var db = new sqlite.Database(‘temp.db’)

module.exports = {
search: function(next) {
db.serialize(function(){
db.all(‘SELECT * FROM TEMP’, function(err, rows) {
if(err) {
console.log(«err: «, err)
throw err
}
rows.forEach(function (row) {
console.log(row)
})
closeDb()
next(err, rows)
})
})
}
}

function closeDb(rows) {
console.log(«closeDb»)
db.close()
}


Reply to this email directly or view it on GitHub:
#441

@devanp92

Hi, sorry for the lack of information. Here is what I have:

    $ sqlite3 temp.db

sqlite> .tables
temp

sqlite> .schema temp;
CREATE TABLE temp (a TEXT, b REAL, c TEXT, d TEXT, e REAL, PRIMARY KEY(a, b, c));

sqlite> select count(*) from temp;
563

My insert statements imitate:
insert or ignore into temp values (‘string’,0,’another string’,’another string’,-1.0);

@springmeyer

the behavior of sqlite3 core is to create a db if it does not already exist. So what is likely happening is that the path to the temp.db is wrong and a new one is being created.

@letladi

I was having a similar problem and ended up here, the following seems to solve the problem for me (assuming you want to create a table called ‘boards’);

db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='boards'", (err, boardTable)=> {
  if (boardTable === undefined) {
    db.run(`CREATE TABLE boards (
      id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
      name TEXT NOT NULL,
      starred INTEGER NOT NULL DEFAULT 0
    );`);
  }
});

@christophemarois

In my case too, I was referring to the location using a relative path ../dev.sqlite3. Changing it for path.resolve(__dirname, '../dev.sqlite3') fixed it

eugenehp, janzenz, vhrustic, denialromeo, cwinters8, xavierbriole, jess-perina, gate3, Adohk, frmh0313, and 23 more reacted with thumbs up emoji
janzenz, vuhung3990, denialromeo, hungryogre, xavierbriole, gate3, mecosteas, jochri3, gaiveknopf, DiogoMarianoLagassi, and 8 more reacted with hooray emoji
whthT, janzenz, anuranBarman, denialromeo, xavierbriole, jess-perina, gate3, TryingUser, flavsxavier, shakhawatfci, and 9 more reacted with heart emoji
jochri3, gaiveknopf, DiogoMarianoLagassi, eightyfive, shepardm7, destroierdam, noddysouthgate, Dianliyeva, and MoustaphaDev reacted with rocket emoji

@janzenz

Thanks! @christophemarois

Thanks for this library as well. However, it would have been helpful to know if the logs would have indicated that the DB file wasn’t found and that a new database have been created instead would have save time debugging this error.

@stiofand

Ive not managed to get sqlite working in Mac Mojave and latest Node at all, always no table found, and no solutions offered.

It seems to create the Db and the table, but any actions after that it throws a ‘no such table’ error

@shsma

@springmeyer did you try either to await the sync or to trigger the function chaining once the sync promise is resolved?

await Address.sync({ force : true }); // drops addresses table and re-creates it

   Address.sync({ force : true }).then(async () => {
     // your logic here
    }); 

@LeonardoGentile

Experiencing a similar problem and the above solution didn’t work for me.

@tksilicon

path.resolve(__dirname, ‘../dev.sqlite3’

Solves the problem

@shakhawatfci

In my case too, I was referring to the location using a relative path ../dev.sqlite3. Changing it for path.resolve(__dirname, '../dev.sqlite3') fixed it

thanks man this save my day

@stock-dd

the behavior of sqlite3 core is to create a db if it does not already exist. So what is likely happening is that the path to the temp.db is wrong and a new one is being created.

Strange behaviour. More logical would be to throw an error with the erroneous path.

Понравилась статья? Поделить с друзьями:
  • Sql ошибка входа пользователя гость
  • Sql ошибка 9694
  • Sql ошибка 42601
  • Sql ошибка 7416
  • Sql ошибка 5173