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)

Пишу систему регистрации для ТГ бота, создал базу данных, все что нужно написал и запускаю и ошибка 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
Не пойму: В чём ошибка, если таблица существует…
Подскажите, кто знает.

@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.

  • Remove From My Forums
  • Question

  • Hello, I tried to use Entity Framework Core and SQLite, when I deploy the program, it contains error SQLite Error 1: ‘no such table: Goal’ on this line:

    public static List<Goal> GetGoals()
    {
        using (var db = new GoalDataContext())
            return db.Goals.ToList(); //this line
    }

    Goals is my Table name.

    This is my Goal class that I have migrated:

    [Table("Goal")]
        public class Goal
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int GoalId { get; set; }
    
            public string nama { get; set; }
            public double berat { get; set; }
            public double tinggi { get; set; }
            public int umur { get; set; }
            public string gender { get; set; }
            public double calorieGoal { get; set; }
            public double calorieToday { get; set; }
    
            public List<GoalTracker> GoalTrackers { get; set; }
        }

    and this is the GoalDataContext class:

    public class GoalDataContext : DbContext
        {
            public DbSet<Goal> Goals { get; set; }
            public DbSet<GoalTracker> GoalTrackers { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlite("Filename=CalorieTracker.db");
            }
        }

    • Edited by

      Monday, December 12, 2016 3:00 PM
      adding class code

Answers

  • Finally! I found what’s wrong with my code!

    The name of table on class should same with the name of table on migration.

    I recheck on migration output and Goal class, the name is different, so I re-migrated after edit it.

    • Proposed as answer by
      Barry Wang
      Tuesday, December 13, 2016 8:36 AM
    • Marked as answer by
      Olivia Olga
      Wednesday, December 14, 2016 2:35 AM

BloodyMaria


  • #1

Всем добрый день!

Недавно изучаю Питон, решила попробовать разобраться с базами данных на примере встроенного SQLite3, для чего написала вот такой скрипт:

import os
import sqlite3

a = int(5)
b = «абвгд»
way = os.getcwd()
print (way)

conn = sqlite3.connect(«Test.db»)
cursor = conn.cursor()
if «Test.db» not in os.listdir():
cursor.execute(«CREATE TABLE Test (testint int(1), testvar varchar (10))»)
conn.commit()
base = str(way)+»Test.db»
if os.path.exists(base):
print(«База найдена»)
else:
print(«Неверный путь»)

sql = «INSERT INTO Test VALUES(?,?);»
cursor.execute(sql, (a, b))
conn.commit()

sql = «SELECT testvar FROM Test WHERE testint = 5 LIMIT 1»
cursor.execute(sql)
b = cursor.fetchall()
print(b)

Идея была в том, чтобы создать ДБ, занести в неё данные и тут же проверить, как они считываются. Но на этапе попытки записать данные стандартный Python Shell выдаёт следующее со ссылкой на строку 27: sqlite3.OperationalError: no such table: Test
При этом в папке, откуда я запускаю скрипт, Test.db успешно создаётся, я её там вижу. Пробовала ещё раз указывать путь к папке перед sql-запросом, но это, ожидаемо, не помогло. os.path.exists файл тоже видит. Может, у меня создаётся файл без таблицы Test в нём? Но если да, то что я делаю не так при создании базы? Версия pip 20.01.01
Пробовала прописывать INSERT INTO Test.db — не помогает. Каким-то образом у меня получилось пару раз добиться того, чтобы всё заработало, но потом я решила прописать sql-запрос в отдельной переменной, увидев такой вариант на формуах, и теперь опять ничего не работает. Причём и при попытке убрать переменную sql и прописать запрос сразу в cursor.execute — тоже.

Насколько вообще sqlite3 нежный в плане синтаксиса запроса?

Последнее редактирование: Июл 15, 2020

Понравилась статья? Поделить с друзьями:
  • Sql запрос завершен с ошибками
  • Sqlite ошибка database is locked
  • Sqlcmd при соединении с сервером произошла ошибка
  • Sql выдает ошибку при восстановлении баз
  • Sql строка подключения с ошибкой