При подтверждении данных произошла ошибка no such table main

Перейти к контенту

I have created a Linq and SQLite app in C#/winform with DBLinq using these two commands:

DbMetal /provider:Sqlite /conn "Data Source=pathtodatabase.s3db" /dbml:pathtoDatabase.dbml

and:

DbMetal /code:pathtoDatabaseContext.cs pathtoDatabase.dbml

To get a connection to database:

string dataSource = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "database.s3db";
var connection = new SQLiteConnection(dataSource);
Main db = new Main(connection, new SqliteVendor());

And to query database:

var user = db.User.SingleOrDefault(u => u.UserName == username);

Running this line of code, I get No shuch table Exception:

no such table: main.USER
System.Data.SQLite.SQLiteException was unhandled HResult=-2147467259 Message=SQLite error
no such table: main.USER
Source=System.Data.SQLite 
ErrorCode=-2147467259
StackTrace:
    at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, String& strRemain)
    at System.Data.SQLite.SQLiteCommand.BuildNextCommand()        
    at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
    at System.Data.SQLite.SQLiteDataReader.NextResult()
    at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
    at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
    at System.Data.SQLite.SQLiteCommand.ExecuteDbDataReader(CommandBehavior behavior)
    at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
    at DbLinq.Data.Linq.Sugar.Implementation.QueryRunner.Select[T](SelectQuery selectQuery)
    at DbLinq.Data.Linq.Sugar.Implementation.QueryRunner.SelectSingle[S](SelectQuery selectQuery, Boolean allowDefault)
    at DbLinq.Data.Linq.Sugar.Implementation.QueryRunner.SelectScalar[S](SelectQuery selectQuery)
    at DbLinq.Data.Linq.Implementation.QueryProvider`1.Execute[TResult](Expression expression)
    at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
...

Database file exists and I have the table.
Any Idea?

Цитата
Сообщение от Горесборщик
Посмотреть сообщение

я так и сделал. покажите где это писать, вдруг я не туда вписал?

Возможно, Вы создали таблицу в БД на SQL-сервере. Но в контексте она не появится автоматически — ее надо туда добавить, выбрав опцию «обновить модель из БД» в конструкторе EDM и поставить на ней галочку.

Модель в общем случае может состоять из двух частей.
1 — та, которая добавляется средствами EF и состоит из содержимого папки .edmx (классы модели + контекст).
Все модели этой части привязаны в контексту и отслеживаются EF. Если были внесены любые изменения в эти модели и дан один SaveChanges, то все эти изменения из буфера будут переноситься в БД «скопом», — EF сам создаст для них нужные запросы Update/Insert/Delete и сам же запакует их в одну транзакцию.
2 — добавленные руками классы, которые нужны для алгоритма приложения, но которых нет в самой БД. Например, запросы, возвращающие выборку из нескольких связанных таблиц. Эти классы лежат обычно в папке Models, но не в папке .edmx, а методы для работы с ними — в специальном классе-интерфейсе, называемом репозиторием. Ни об этих классах, ни о репозитории, EF не имеет никакого понятия, поэтому работать с ними можно и нужно без EF (для чего собственно и служит репозиторий)

  • Laravel Version: 5.8.12
  • PHP Version: 7.1.23
  • Database Driver & Version: SQLite 3

Description:

When I launch the command php artisan migrate:fresh --seed I have this error:

Dropped all tables successfully.
Migration table created successfully.
Migrating: 2019_04_14_162607_create_users_table
Migrated:  2019_04_14_162607_create_users_table
Migrating: 2019_04_14_163732_create_companies_table
Migrated:  2019_04_14_163732_create_companies_table
Migrating: 2019_04_15_194613_create_tickets_table
Migrated:  2019_04_15_194613_create_tickets_table
Migrating: 2019_04_15_194639_create_statuses_table
Migrated:  2019_04_15_194639_create_statuses_table
Migrating: 2019_04_15_194747_create_categories_table
Migrated:  2019_04_15_194747_create_categories_table
Migrating: 2019_04_15_195429_create_severities_table
Migrated:  2019_04_15_195429_create_severities_table
Migrating: 2019_04_15_202912_create_messages_table
Migrated:  2019_04_15_202912_create_messages_table
Seeding: UsersTableSeeder
Seeding: SeveritiesTableSeeder
Seeding: StatusesTableSeeder
Seeding: CategoriesTableSeeder
Seeding: TicketsTableSeeder

   IlluminateDatabaseQueryException  : SQLSTATE[HY000]: General error: 1 no such table: main. (SQL: insert into "tickets" ("title", "body", "attachment", "user_id", "severity_id", "status_id", "category_id", "created_at", "updated_at") values (Ea et qui quia quis dolore quo incidunt ullam., Recusandae quasi voluptatem omnis quia ullam dolore exercitationem harum., 77d4b4ef-2668-3b6e-8914-47b87419b98a.img, 73, 4, 2, 1, 2019-04-16 15:44:30, 2019-04-16 15:44:30))

  at /Users/adrienpsn/Dev/Laravel/support-ce/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668| 

  Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1 no such table: main.")
      /Users/adrienpsn/Dev/Laravel/support-ce/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452

  2   PDO::prepare("insert into "tickets" ("title", "body", "attachment", "user_id", "severity_id", "status_id", "category_id", "created_at", "updated_at") values (?, ?, ?, ?, ?, ?, ?, ?, ?)")
      /Users/adrienpsn/Dev/Laravel/support-ce/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452

  Please use the argument -v to see more details.

The error no such table main. comes from my TicketsTableSeederfile because when I don’t call it, I have no error.

Here is my TicketsTableSeeder file:

public function run()
    {
        $faker = FakerFactory::create();

        for ($i = 1; $i < 20; $i++) {
            $title = $faker->sentence(6, true);
            DB::table('tickets')->insert([
                'title' => $title,
                'body' => $faker->text($faker->numberBetween(50, 200)),
                'attachment' => $faker->uuid . '.img',
                'user_id' => $faker->numberBetween(1, 100),
                'severity_id' => $faker->numberBetween(1, 4),
                'status_id' => $faker->numberBetween(1, 7),
                'category_id' => $faker->numberBetween(1, 4),
                'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
                'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
            ]);
        }
    }

Thank’s for any help!

I have also met sqlite «no such table» error on Android 9.0, I have found there is a similar issue on SO. (Android P — ‘SQLite: No Such Table Error’ after copying database from assets).

Base on above link, I tried below solutions 1 and 2.
1) Close connection after read

private void createDataBase() throws IOException {
    this.getReadableDatabase();
    this.close(); 
    try {           
        copyDataBase();            
    } catch (IOException e) {           
       throw new RuntimeException(e);
    }
}

2) Disable WAL.

@Override
public void onConfigure(SQLiteDatabase db) {
    Logger.i(TAG, "onConfigure()");
    super.onConfigure(db);
    db.disableWriteAheadLogging();
}

private boolean checkIfDBExists() {
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

public void openDataBase() throws SQLException {
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);

}

After that, I found a problem, These solutions are only fine when I remove installed App, and fresh install App.

When I have installed a buggy App with "no such table error" on Android 9.0 device, Then I add above fixed code, and install it directly with Android Studio which looks like an App upgrade scenario.

In this case, The db file will be over there, checkIfDBExists() will return true, then we will call openDataBase() instead of createDataBase() The sqlite "no such table" error will still happen, So How can I totally fix this issue no matter fresh install or upgrade? Thanks in advance.

I have also met sqlite «no such table» error on Android 9.0, I have found there is a similar issue on SO. (Android P — ‘SQLite: No Such Table Error’ after copying database from assets).

Base on above link, I tried below solutions 1 and 2.
1) Close connection after read

private void createDataBase() throws IOException {
    this.getReadableDatabase();
    this.close(); 
    try {           
        copyDataBase();            
    } catch (IOException e) {           
       throw new RuntimeException(e);
    }
}

2) Disable WAL.

@Override
public void onConfigure(SQLiteDatabase db) {
    Logger.i(TAG, "onConfigure()");
    super.onConfigure(db);
    db.disableWriteAheadLogging();
}

private boolean checkIfDBExists() {
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

public void openDataBase() throws SQLException {
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);

}

After that, I found a problem, These solutions are only fine when I remove installed App, and fresh install App.

When I have installed a buggy App with "no such table error" on Android 9.0 device, Then I add above fixed code, and install it directly with Android Studio which looks like an App upgrade scenario.

In this case, The db file will be over there, checkIfDBExists() will return true, then we will call openDataBase() instead of createDataBase() The sqlite "no such table" error will still happen, So How can I totally fix this issue no matter fresh install or upgrade? Thanks in advance.

Skip to forum content

My Visual Database

A Simple Solution for Creating Databases

You are not logged in. Please login or register.

Active topics Unanswered topics

Pages 1

You must login or register to post a reply

1 2015-01-12 12:10:12

  • iliasidash
  • Member
  • Offline
  • Registered: 2015-01-09
  • Posts: 14

Topic: No such table

В чем может быть причина… При запуске программы выдает «No such table «Название таблицы». Таблица есть ссылки все проверил, не могу понять в чем дело!

2 Reply by iliasidash 2015-01-12 12:12:38

  • iliasidash
  • Member
  • Offline
  • Registered: 2015-01-09
  • Posts: 14

Re: No such table

Добрый день!!!!
Забылся немного))))

3 Reply by DriveSoft 2015-01-12 12:16:21

  • DriveSoft
  • DriveSoft
  • Administrator
  • Offline
  • Registered: 2014-02-14
  • Posts: 10,294

Re: No such table

В текущей версии при изменении структуры БД, необходимо пересоздавать базу данных, при этом все данные в ней теряются.

После того, как вы изменили структуру существующей БД (например добавили новую таблицу), и запустили проект, Вы должны были получить сообщение:

Структура базы данных была изменена.
Вы желаете пересоздать базу данных?
—————————
Yes   No   
—————————

Скорей всего вы ответили No, и структура базы данных фактически не была изменена (в файле sqlite.db)
Просто удалите файл базы данных в папке с проектом sqlite.db и при запуске проекта БД будет пересоздана правильно.

В последней бета версии 1.48 эта проблема почти решена
— Реализована возможность создания новых полей в БД без потери данных (08.01.2015)
— Реализована возможность создания и удаления таблиц в БД без потери данных (09.01.2015)
— Реализована возможность удаления полей из таблиц БД без потери данных (10.01.2015)
Осталось реализовать возможность переименования полей и таблиц без потери данных в БД.

Скачать бета версию 1.48 можете здесь
http://myvisualdatabase.com/forum/viewtopic.php?id=781

Dmitry.

4 Reply by Leonid 2015-01-12 14:33:12

  • Leonid
  • Member
  • Offline
  • Registered: 2014-07-11
  • Posts: 99

Re: No such table

Уже попробовал ! Здорово ! Спасибо !

5 Reply by iliasidash 2015-01-12 15:44:16

  • iliasidash
  • Member
  • Offline
  • Registered: 2015-01-09
  • Posts: 14

Re: No such table

Большое спасибо!

Posts: 5

Pages 1

You must login or register to post a reply

  • 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

Привет, я пытаюсь освоить джанго и нахожусь на этапе добавления тестового «продукта» в режиме админа.

Зашел в 127.0.0.1:8000/admin далее в разделе Products который создал ранее в admin.py

from django.contrib import admin
from .models import Product
admin.site.register(Product)

а также в models.py

class Offer(models.Model):
    code = models.CharField(max_length=10)
    description = models.CharField(max_length=255)
    discount = models.FloatField()

… нажимаю + Add

далее заполняю все необходимые поля, жму на Save и … получаю вот такую ошибку:

OperationalError at /admin/products/product/add/
no such table: main.auth_user__old
Request Method:	POST
Request URL:	http://127.0.0.1:8000/admin/products/product/add/
Django Version:	2.1
Exception Type:	OperationalError
Exception Value:	
no such table: main.auth_user__old
Exception Location:	C:UsersdmitrPycharmProjectsPyShopvenvlibsite-packagesdjangodbbackendssqlite3base.py in execute, line 296
Python Executable:	C:UsersdmitrPycharmProjectsPyShopvenvScriptspython.exe
Python Version:	3.7.4
Python Path:	
['C:\Users\dmitr\PycharmProjects\PyShop',
 'C:\Users\dmitr\AppData\Local\Programs\Python\Python37-32\python37.zip',
 'C:\Users\dmitr\AppData\Local\Programs\Python\Python37-32\DLLs',
 'C:\Users\dmitr\AppData\Local\Programs\Python\Python37-32\lib',
 'C:\Users\dmitr\AppData\Local\Programs\Python\Python37-32',
 'C:\Users\dmitr\PycharmProjects\PyShop\venv',
 'C:\Users\dmitr\PycharmProjects\PyShop\venv\lib\site-packages',
 'C:\Users\dmitr\PycharmProjects\PyShop\venv\lib\site-packages\setuptools-39.1.0-py3.7.egg',
 'C:\Users\dmitr\PycharmProjects\PyShop\venv\lib\site-packages\pip-10.0.1-py3.7.egg']
Server time:	Sat, 23 May 2020 22:35:43 +0000

посмотрел на стэке (https://stackoverflow.com/questions/36123312/djang…) — там говорят что всего лишь надо

python manage.py migrate

python manage.py makemigrations
python manage.py migrate

Но это не помогает…

Проблема какая-то совсем простая но не пойму в чем дело.

Спасибо!

I have created a Linq and SQLite app in C#/winform with DBLinq using these two commands:

DbMetal /provider:Sqlite /conn "Data Source=pathtodatabase.s3db" /dbml:pathtoDatabase.dbml

and:

DbMetal /code:pathtoDatabaseContext.cs pathtoDatabase.dbml

To get a connection to database:

string dataSource = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "database.s3db";
var connection = new SQLiteConnection(dataSource);
Main db = new Main(connection, new SqliteVendor());

And to query database:

var user = db.User.SingleOrDefault(u => u.UserName == username);

Running this line of code, I get No shuch table Exception:

no such table: main.USER
System.Data.SQLite.SQLiteException was unhandled HResult=-2147467259 Message=SQLite error
no such table: main.USER
Source=System.Data.SQLite 
ErrorCode=-2147467259
StackTrace:
    at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, String& strRemain)
    at System.Data.SQLite.SQLiteCommand.BuildNextCommand()        
    at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
    at System.Data.SQLite.SQLiteDataReader.NextResult()
    at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
    at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
    at System.Data.SQLite.SQLiteCommand.ExecuteDbDataReader(CommandBehavior behavior)
    at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
    at DbLinq.Data.Linq.Sugar.Implementation.QueryRunner.Select[T](SelectQuery selectQuery)
    at DbLinq.Data.Linq.Sugar.Implementation.QueryRunner.SelectSingle[S](SelectQuery selectQuery, Boolean allowDefault)
    at DbLinq.Data.Linq.Sugar.Implementation.QueryRunner.SelectScalar[S](SelectQuery selectQuery)
    at DbLinq.Data.Linq.Implementation.QueryProvider`1.Execute[TResult](Expression expression)
    at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
...

Database file exists and I have the table.
Any Idea?

  • Laravel Version: 5.8.12
  • PHP Version: 7.1.23
  • Database Driver & Version: SQLite 3

Description:

When I launch the command php artisan migrate:fresh --seed I have this error:

Dropped all tables successfully.
Migration table created successfully.
Migrating: 2019_04_14_162607_create_users_table
Migrated:  2019_04_14_162607_create_users_table
Migrating: 2019_04_14_163732_create_companies_table
Migrated:  2019_04_14_163732_create_companies_table
Migrating: 2019_04_15_194613_create_tickets_table
Migrated:  2019_04_15_194613_create_tickets_table
Migrating: 2019_04_15_194639_create_statuses_table
Migrated:  2019_04_15_194639_create_statuses_table
Migrating: 2019_04_15_194747_create_categories_table
Migrated:  2019_04_15_194747_create_categories_table
Migrating: 2019_04_15_195429_create_severities_table
Migrated:  2019_04_15_195429_create_severities_table
Migrating: 2019_04_15_202912_create_messages_table
Migrated:  2019_04_15_202912_create_messages_table
Seeding: UsersTableSeeder
Seeding: SeveritiesTableSeeder
Seeding: StatusesTableSeeder
Seeding: CategoriesTableSeeder
Seeding: TicketsTableSeeder

   IlluminateDatabaseQueryException  : SQLSTATE[HY000]: General error: 1 no such table: main. (SQL: insert into "tickets" ("title", "body", "attachment", "user_id", "severity_id", "status_id", "category_id", "created_at", "updated_at") values (Ea et qui quia quis dolore quo incidunt ullam., Recusandae quasi voluptatem omnis quia ullam dolore exercitationem harum., 77d4b4ef-2668-3b6e-8914-47b87419b98a.img, 73, 4, 2, 1, 2019-04-16 15:44:30, 2019-04-16 15:44:30))

  at /Users/adrienpsn/Dev/Laravel/support-ce/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668| 

  Exception trace:

  1   PDOException::("SQLSTATE[HY000]: General error: 1 no such table: main.")
      /Users/adrienpsn/Dev/Laravel/support-ce/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452

  2   PDO::prepare("insert into "tickets" ("title", "body", "attachment", "user_id", "severity_id", "status_id", "category_id", "created_at", "updated_at") values (?, ?, ?, ?, ?, ?, ?, ?, ?)")
      /Users/adrienpsn/Dev/Laravel/support-ce/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452

  Please use the argument -v to see more details.

The error no such table main. comes from my TicketsTableSeederfile because when I don’t call it, I have no error.

Here is my TicketsTableSeeder file:

public function run()
    {
        $faker = FakerFactory::create();

        for ($i = 1; $i < 20; $i++) {
            $title = $faker->sentence(6, true);
            DB::table('tickets')->insert([
                'title' => $title,
                'body' => $faker->text($faker->numberBetween(50, 200)),
                'attachment' => $faker->uuid . '.img',
                'user_id' => $faker->numberBetween(1, 100),
                'severity_id' => $faker->numberBetween(1, 4),
                'status_id' => $faker->numberBetween(1, 7),
                'category_id' => $faker->numberBetween(1, 4),
                'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
                'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
            ]);
        }
    }

Thank’s for any help!

Цитата
Сообщение от Горесборщик
Посмотреть сообщение

я так и сделал. покажите где это писать, вдруг я не туда вписал?

Возможно, Вы создали таблицу в БД на SQL-сервере. Но в контексте она не появится автоматически — ее надо туда добавить, выбрав опцию «обновить модель из БД» в конструкторе EDM и поставить на ней галочку.

Модель в общем случае может состоять из двух частей.
1 — та, которая добавляется средствами EF и состоит из содержимого папки .edmx (классы модели + контекст).
Все модели этой части привязаны в контексту и отслеживаются EF. Если были внесены любые изменения в эти модели и дан один SaveChanges, то все эти изменения из буфера будут переноситься в БД «скопом», — EF сам создаст для них нужные запросы Update/Insert/Delete и сам же запакует их в одну транзакцию.
2 — добавленные руками классы, которые нужны для алгоритма приложения, но которых нет в самой БД. Например, запросы, возвращающие выборку из нескольких связанных таблиц. Эти классы лежат обычно в папке Models, но не в папке .edmx, а методы для работы с ними — в специальном классе-интерфейсе, называемом репозиторием. Ни об этих классах, ни о репозитории, EF не имеет никакого понятия, поэтому работать с ними можно и нужно без EF (для чего собственно и служит репозиторий)

  • При подписке на событие передзаписью произошла ошибка обработчик события не найден
  • При подписке на событие обработкаполученияформы произошла ошибка обработчик события не найден
  • При подписи эцп выдает ошибку
  • При подписи произошла ошибка visual studio
  • При подписи документа эцп возникает ошибка превышение размера