Ошибка вставки строки not an error

Comments

@VortixDev

@VortixDev
VortixDev

changed the title
«no error» on SQL import

«not an error» on SQL import

Aug 26, 2018

@justinclift
justinclift

added
the

bug

Confirmed bugs or reports that are very likely to be bugs.

label

Aug 26, 2018

MKleusberg

added a commit
that referenced
this issue

Aug 27, 2018

@MKleusberg

This commit fixed wrong error messages in the code we use whenever
multiple SQL statements are executed at once programmatically, most
noticeably in the SQL import. In the case of an error we would first
clean up and rollback and only then recover the error message which
usually would be lost by then. With the changes in this commit the first
thing we do is to recover the error message and only then clean up.

See issue #1519.

MKleusberg

added a commit
that referenced
this issue

Aug 28, 2018

@MKleusberg

When importing an SQL file, defer foreign keys until the import is
finished. This is necessary if there are foreign key constraints in the
imported table and the order of the INSERT statements doesn't match the
hierarchy of the constraints.

Also perform an integrity check at the end of the import.

See issue #1519.

More SQLite issues. So my interface is as follows (this is all in .m):

@interface Search()
    @property (strong, nonatomic) NSString *databasePath; //path to sqlite database file
    @property (strong, nonatomic) NSString *databaseName;
    @property (nonatomic) sqlite3 *database;
@end

and the init follows:

- (id)init
{
    if ((self = [super init]))
    {
        self.databaseName = DB_NAME;

        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        _databasePath = [documentsDir stringByAppendingPathComponent:self.databaseName];
        [self checkAndCreateDatabase];
        if (sqlite3_open_v2([self.databasePath UTF8String], &_database, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK)
        {
            [[[UIAlertView alloc]initWithTitle:@"Missing"
                                       message:@"Database file not found"
                                      delegate:nil
                             cancelButtonTitle:@"OK"
                             otherButtonTitles:nil, nil]show];
        }
        else
        {
            NSLog(@"%s: sqlite3_open_v2 error: %s", __FUNCTION__, sqlite3_errmsg(self.database));
        }
    }

The error that the Log in the init returns is: sqlite3_open_v2 error: not an error. In my searches, I’ve heard that SQLite doesn’t return an error when it points to a non-existent database. But I’m not sure why the database wouldn’t exist. The copy function I’m using (which I was given and had seemed to work before) is as follows:

-(void) checkAndCreateDatabase
{
    // Check if the SQL database has already been saved to the users phone, if not then copy it over
    BOOL dbExists;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    dbExists = [fileManager fileExistsAtPath:_databasePath];

    // If the database already exists then return without doing anything
    if(dbExists)
    {
        return;
    }
    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];

    // Copy the database from the package to the users filesystem
    //[fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];
    NSError *error = nil;
    if (![fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:&error])
    {
        NSLog(@"%s: copyItemAtPathError: %@", __FUNCTION__, error);
    }
}

Finally, I have verified in the iOS Simulator Documents directory that the database exists, and the query I’m trying to execute on it works. Why might I be getting this error?

Иногда при вставке строки я получаю SQLiteMisuseException. Приложение отлично работает на сотнях устройств, но на одном с Android 3.1 есть исключение SQLite. Трассировки стека:

    android.database.sqlite.SQLiteMisuseException: error code 21: not an error
    at android.database.sqlite.SQLiteStatement.native_executeInsert(Native Method)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:112)

Это код, вызывающий executeInsert ():

    final SQLiteStatement insUrlStmt = db.compileStatement("insert into urls (url,idx) values (?,?)");
    insUrlStmt.bindString(1, url)
    insUrlStmt.bindLong(2, idx);
    return insUrlStmt.executeInsert();

Объявление поля db:

    private final SQLiteDatabase db;

Инициализация поля db (вызывается один раз в onCreate () объекта класса Application), а ссылка на DataHelper сохраняется статически в экземпляре приложения:

    public DataHelper(Context context) {db = new OpenHelper(context).getWritableDatabase();   }

Конструктор OpenHelper:

    protected OpenHelper(Context context) 
{
     super(context, "database.db", null, 1);       
}

Я уже читал этот вопрос: Код ошибки Android SQLite 21 и искал упомянутые там вещи.

SQLiteDatabase (поле db) открывается только один раз и никогда не закрывается непосредственно из кода приложения. Многопоточный доступ не должен быть проблемой, потому что первым делом в методе executeInsert () является блокировка базы данных (я проверил исходный код android 2.1, поэтому предполагаю, что это поведение не изменилось в 3.1).

Иногда я получаю исключение SQLiteMisuseException при вставке строки. Приложение работает отлично на сотнях устройств, но на одном с Android 3.0 есть исключение SQLite. Трассировки стека:

    android.database.sqlite.SQLiteMisuseException: error code 21: not an error
at android.database.sqlite.SQLiteStatement.native_executeInsert(Native Method)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:112)

Это код, который вызывает executeInsert():

    final SQLiteStatement insUrlStmt = db.compileStatement("insert into urls (url,idx) values (?,?)");
insUrlStmt.bindString(1, url)
insUrlStmt.bindLong(2, idx);
return insUrlStmt.executeInsert();

Объявление поля db:

    private final SQLiteDatabase db;

Инициализация поля db (это вызывается один раз в onCreate() объекта класса Application), а ссылка на DataHelper хранится статически в экземпляре приложения:

    public DataHelper(Context context) {db = new OpenHelper(context).getWritableDatabase();   }

Конструктор OpenHelper:

    protected OpenHelper(Context context) 
{
super(context, "database.db", null, 1);
}

Я уже прочитал этот вопрос: код ошибки Android SQLite 21 и искал все, что упоминалось там.

SQLiteDatabase (поле db) открывается только один раз и никогда не закрывается непосредственно из кода приложения. Многопоточный доступ не должен быть проблемой, потому что первая вещь в методе executeInsert() — это блокировка базы данных (я проверял исходный код Android 2.1, поэтому я предполагаю, что это поведение не изменилось в 3.1).

Hi, Every One…

while run my ASP.net application with C#.. I got one error like below..
————————————————————————————

System.Data.SqlClient.SqlException was unhandled by user code
  Message="Incorrect syntax near 'S'."
  Source=".Net SqlClient Data Provider"
  ErrorCode=-2146232060
  Class=15
  LineNumber=1
  Number=102
  Procedure=""
  Server="PINNACLESERVERSQLEXPRESS"
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at Ad_Defaulters.Page_Init(Object sender, EventArgs e) in c:Documents and SettingspcDesktop123Ad_Defaulters.aspx.cs:line 53
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnInit(EventArgs e)
       at System.Web.UI.Page.OnInit(EventArgs e)
       at System.Web.UI.Control.InitRecursive(Control namingContainer)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 

————————————————————————————
How to resolve this error

In this me inserting a 4000 rows in a table.
after insert 1783 rows, the error coming like this

Incorrect syntax near ‘S’.

Updated 20-Jun-12 22:08pm


This is due to special characters. In your 1784th row there is a '. Either you use YOURSTRING.Replace("'","''") or you need to use parameterized query.

Parameterized-Queries[^]

Regards
Sebastian

Updated 20-Jun-12 21:08pm

[Answering a follow-up question:]

Parametrized query is one of the very critical aspects of database programming, so you have to learn it. Please start here:
http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx[^].

This is related not just to the problems like yours. One of the most critical problem solved with parametrized statements is related to security. Actually, if you compose your command based on user-supplied data, it can be anything, including some SQL code, which opens wide doors to a well-known exploit called SQL injection. This article explains the importance of parametrized statements:
http://en.wikipedia.org/wiki/SQL_injection#Parameterized_statements[^].

—SA

Updated 20-Jun-12 21:31pm

This is problem with using » ‘ » in your inserting value.It might be happen that character is exist in your 1784th rows.If that character is exist in your first Rows , you can’t insert first rows.

So, better approach is using Stored Procedure for Inserting your records in Table in stead of using direct query.

Go through http://msdn.microsoft.com/en-us/library/ms345415.aspx[^] for creating a stored procedure.

use link http://support.microsoft.com/kb/320916[^] to call Stored Procedure through your code.

sqlcon.Open();
for (int i = 0; i < dtMfcStand.Rows.Count; i++)
{
    string str;
    str = "insert into TableName values(";
    for (int j = 0; j < dtMfcStand.Columns.Count; j++)
    {
        string dtstr = dtMfcStand.Rows[i][j].ToString().Replace("'", "");
        str += "'" + dtstr + "',";

    }
    str += ")";
    string str1 = str.Replace(",)", ")");

    SqlCommand cmd = new SqlCommand(str1, sqlcon);
    int k = cmd.ExecuteNonQuery();
}
lblMessage.Text = "Suucessfully Inserted in Database.";
sqlcon.Close();

Updated 20-Jun-12 22:21pm

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Hi, Every One…

while run my ASP.net application with C#.. I got one error like below..
————————————————————————————

System.Data.SqlClient.SqlException was unhandled by user code
  Message="Incorrect syntax near 'S'."
  Source=".Net SqlClient Data Provider"
  ErrorCode=-2146232060
  Class=15
  LineNumber=1
  Number=102
  Procedure=""
  Server="PINNACLESERVERSQLEXPRESS"
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at Ad_Defaulters.Page_Init(Object sender, EventArgs e) in c:Documents and SettingspcDesktop123Ad_Defaulters.aspx.cs:line 53
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnInit(EventArgs e)
       at System.Web.UI.Page.OnInit(EventArgs e)
       at System.Web.UI.Control.InitRecursive(Control namingContainer)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 

————————————————————————————
How to resolve this error

In this me inserting a 4000 rows in a table.
after insert 1783 rows, the error coming like this

Incorrect syntax near ‘S’.

Updated 20-Jun-12 22:08pm


This is due to special characters. In your 1784th row there is a '. Either you use YOURSTRING.Replace("'","''") or you need to use parameterized query.

Parameterized-Queries[^]

Regards
Sebastian

Updated 20-Jun-12 21:08pm

[Answering a follow-up question:]

Parametrized query is one of the very critical aspects of database programming, so you have to learn it. Please start here:
http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx[^].

This is related not just to the problems like yours. One of the most critical problem solved with parametrized statements is related to security. Actually, if you compose your command based on user-supplied data, it can be anything, including some SQL code, which opens wide doors to a well-known exploit called SQL injection. This article explains the importance of parametrized statements:
http://en.wikipedia.org/wiki/SQL_injection#Parameterized_statements[^].

—SA

Updated 20-Jun-12 21:31pm

This is problem with using » ‘ » in your inserting value.It might be happen that character is exist in your 1784th rows.If that character is exist in your first Rows , you can’t insert first rows.

So, better approach is using Stored Procedure for Inserting your records in Table in stead of using direct query.

Go through http://msdn.microsoft.com/en-us/library/ms345415.aspx[^] for creating a stored procedure.

use link http://support.microsoft.com/kb/320916[^] to call Stored Procedure through your code.

sqlcon.Open();
for (int i = 0; i < dtMfcStand.Rows.Count; i++)
{
    string str;
    str = "insert into TableName values(";
    for (int j = 0; j < dtMfcStand.Columns.Count; j++)
    {
        string dtstr = dtMfcStand.Rows[i][j].ToString().Replace("'", "");
        str += "'" + dtstr + "',";

    }
    str += ")";
    string str1 = str.Replace(",)", ")");

    SqlCommand cmd = new SqlCommand(str1, sqlcon);
    int k = cmd.ExecuteNonQuery();
}
lblMessage.Text = "Suucessfully Inserted in Database.";
sqlcon.Close();

Updated 20-Jun-12 22:21pm

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Как упоминалось в комментариях, вы не можете добавить столбец в представление с помощью команды insert. Команда insert вставляет данные в таблицу. Представление — это проекция команды выбора, поэтому для вставки столбца в представление необходимо изменить представление. Так и должно быть:

create or replace view details
 as
SELECT null as pSerial_number, 
       null as pname,
       NULL AS additional_field1 
from student;

Этого достаточно, чтобы добавить в это представление additional_field1.

Проблема здесь в том, что ваше представление вообще не имеет смысла, потому что оно перечисляет все строки из таблицы student как nulls для этих трех полей, введенных вручную.

Например, скажем, что структура таблицы student

serial_number varchar,
name varchar,
additional_field1 int

И значения в нем следующие:

serial_number   name    additional_field1
   AD5424       Test1      1
   AD5421       Test2      2
   AD5422       Test3      3

Если вы запустите приведенный выше код (для создания представления), а затем запустите на нем оператор select, например select * from details, ответ, который вы получите, будет следующим:

serial_number   name    additional_field1
   null         null      null
   null         null      null
   null         null      null

Поэтому вместо этого вы сопоставляете свое представление с соответствующими столбцами таблицы следующим образом:

create or replace view details
 as
SELECT serial_number as pSerial_number, 
       name as pname,
       additional_field1 AS additional_field1 
from student;

И теперь, если вы запустите оператор select на нем select * from details, вы получите:

pSerial_number   pname    additional_field1
   AD5424       Test1      1
   AD5421       Test2      2
   AD5422       Test3      3

Обратите внимание на названия столбцов и значения таблицы учеников.

Надеюсь, это поможет прояснить, что такое представление и как вы можете его изменить.

Я новичок в Postgresql и каждый день узнаю что-то новое. Итак, у меня есть этот блог-проект, в котором я хочу использовать PostgreSQL как базу данных. Но я как бы застрял в самом простом запросе вставки, который выдает ошибку. У меня есть три стола: posts, authors и categories. Думаю, я мог бы правильно создать таблицу, но когда я пытаюсь вставить данные, я получаю эту ошибку:

error: syntax error at or near 
length: 95,
  severity: 'ERROR',
  code: '42601',
  detail: undefined,
  hint: undefined,
  position: '122',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'scan.l',
  line: '1180',
  routine: 'scanner_yyerror'

Теперь я не знаю, в чем проблема, и ошибки Postgres не так уж специфичны.

Кто-нибудь может сказать мне, где я могу ошибиться?

Вот таблицы:

const createInitialTables = `
        CREATE TABLE authors (
             id UUID NOT NULL,
             author_name VARCHAR(100) NOT NULL UNIQUE CHECK (author_name <> ''),
             author_slug VARCHAR(100) NOT NULL UNIQUE CHECK (author_slug <> ''),
             PRIMARY KEY (id)
        );

        CREATE TABLE posts (
             id UUID NOT NULL,
             post VARCHAR(500) NOT NULL CHECK (post<> ''),
             post_slug VARCHAR(500) NOT NULL CHECK (post_slug <> ''),
             author_id UUID NOT NULL,
             PRIMARY KEY (id),
             CONSTRAINT fk_authors FOREIGN KEY(author_id) REFERENCES authors(id)
        );

        CREATE TABLE categories (
             id UUID NOT NULL,
             category_name VARCHAR(50) NOT NULL CHECK (category_name <> ''),
             category_slug VARCHAR(50) NOT NULL CHECK (category_slug <> ''),
             post_id UUID NOT NULL,
             PRIMARY KEY (id),
             CONSTRAINT fk_posts FOREIGN KEY(post_id) REFERENCES posts(id)
        );

`;

Вот асинхронная функция, в которой я делаю запрос на вставку:

const insertAuthor = async() => {

    try {

        const data       = await fs.readFile( path.join( __dirname + '../../data/data.json' ) );
        const parsedData = JSON.parse( data.toString() );

        const authorID   = short.generate();
        const authorName = parsedData[ 0 ].author;
        const authorSlug = slugify( parsedData[ 0 ].author, {
            strict: true,
            lower: true
        } );

        const insertData = `
            INSERT INTO authors (id, author_name, author_slug) 
            VALUES 
            (${authorID}, ${authorName}, ${authorSlug});
        `;

        await pool.query( insertData );

        console.log( 'Data inserted successfully!' );

    } catch ( e ) {
        console.log( e );
    }
};

insertAuthor();

ОБНОВИТЬ—————————————

Вот как выглядит файл журнала Postgres:

2021-10-18 01:23:16.885 +06 [5964] ERROR:  syntax error at or near "Paton" at character 122
2021-10-18 01:23:16.885 +06 [5964] STATEMENT:  
                INSERT INTO authors (id, author_name, author_slug) 
                VALUES 
                (an3cxZh8ZD3tdtqG4wuwPR, Alan Paton, alan-paton);

2 ответа

Лучший ответ

INSERT INTO authors (id, author_name, author_slug) 
VALUES 
(an3cxZh8ZD3tdtqG4wuwPR, Alan Paton, alan-paton);

Ваши строковые значения не заключаются в кавычки. Это должно быть …

INSERT INTO authors (id, author_name, author_slug) 
VALUES 
('an3cxZh8ZD3tdtqG4wuwPR', 'Alan Paton', 'alan-paton');

Вы можете добавить кавычки в свой запрос, но не делайте этого. Ваш запрос в том виде, в котором он написан, небезопасен и уязвим для атаки с использованием SQL-инъекции. Не вставляйте значения в запросы с конкатенацией строк .

Вместо этого используйте параметры.

const insertSQL = `
  INSERT INTO authors (id, author_name, author_slug) 
  VALUES ($1, $2, $3);
`;
await pool.query( insertSQL, [authorID, authorName, authorSlug] );

Postgres сделает за вас расценки. Это безопаснее, надежнее и быстрее.


Обратите внимание, что an3cxZh8ZD3tdtqG4wuwPR не является допустимым UUID. UUID — это 128-битное целое число, которое часто представляется в виде 32-символьной шестнадцатеричной строки.

Обратите внимание, что вы также, вероятно, захотите использовать автоинкремент первичных ключей вместо самостоятельного создания идентификатора. Для первичного ключа UUID загрузите пакет uuid-ossp и используйте его функция UUID по умолчанию.

create extension "uuid-ossp";

create table authors (
  id uuid primary key default uuid_generate_v4(),

  -- There's no point in arbitrarily limiting the size of your text fields.
  -- They will only use as much space as they need.
  author_name text not null unique check (author_name <> ''),
  author_slug text not null unique check (author_slug <> '')
);

insert into authors (author_name, author_slug) 
values ('Alan Paton', 'alan-paton');


3

Schwern
17 Окт 2021 в 23:08

В запросе INSERT добавьте строковые значения в кавычки —

const insertData = `
    INSERT INTO authors (id, author_name, author_slug) 
    VALUES 
    ('${authorID}', '${authorName}', '${authorSlug}');`;  // added the quotes


0

Vedant
17 Окт 2021 в 22:43

More SQLite issues. So my interface is as follows (this is all in .m):

@interface Search()
    @property (strong, nonatomic) NSString *databasePath; //path to sqlite database file
    @property (strong, nonatomic) NSString *databaseName;
    @property (nonatomic) sqlite3 *database;
@end

and the init follows:

- (id)init
{
    if ((self = [super init]))
    {
        self.databaseName = DB_NAME;

        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        _databasePath = [documentsDir stringByAppendingPathComponent:self.databaseName];
        [self checkAndCreateDatabase];
        if (sqlite3_open_v2([self.databasePath UTF8String], &_database, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK)
        {
            [[[UIAlertView alloc]initWithTitle:@"Missing"
                                       message:@"Database file not found"
                                      delegate:nil
                             cancelButtonTitle:@"OK"
                             otherButtonTitles:nil, nil]show];
        }
        else
        {
            NSLog(@"%s: sqlite3_open_v2 error: %s", __FUNCTION__, sqlite3_errmsg(self.database));
        }
    }

The error that the Log in the init returns is: sqlite3_open_v2 error: not an error. In my searches, I’ve heard that SQLite doesn’t return an error when it points to a non-existent database. But I’m not sure why the database wouldn’t exist. The copy function I’m using (which I was given and had seemed to work before) is as follows:

-(void) checkAndCreateDatabase
{
    // Check if the SQL database has already been saved to the users phone, if not then copy it over
    BOOL dbExists;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    dbExists = [fileManager fileExistsAtPath:_databasePath];

    // If the database already exists then return without doing anything
    if(dbExists)
    {
        return;
    }
    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];

    // Copy the database from the package to the users filesystem
    //[fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];
    NSError *error = nil;
    if (![fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:&error])
    {
        NSLog(@"%s: copyItemAtPathError: %@", __FUNCTION__, error);
    }
}

Finally, I have verified in the iOS Simulator Documents directory that the database exists, and the query I’m trying to execute on it works. Why might I be getting this error?

Иногда я получаю исключение SQLiteMisuseException при вставке строки. Приложение работает отлично на сотнях устройств, но на одном с Android 3.0 есть исключение SQLite. Трассировки стека:

    android.database.sqlite.SQLiteMisuseException: error code 21: not an error
at android.database.sqlite.SQLiteStatement.native_executeInsert(Native Method)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:112)

Это код, который вызывает executeInsert():

    final SQLiteStatement insUrlStmt = db.compileStatement("insert into urls (url,idx) values (?,?)");
insUrlStmt.bindString(1, url)
insUrlStmt.bindLong(2, idx);
return insUrlStmt.executeInsert();

Объявление поля db:

    private final SQLiteDatabase db;

Инициализация поля db (это вызывается один раз в onCreate() объекта класса Application), а ссылка на DataHelper хранится статически в экземпляре приложения:

    public DataHelper(Context context) {db = new OpenHelper(context).getWritableDatabase();   }

Конструктор OpenHelper:

    protected OpenHelper(Context context) 
{
super(context, "database.db", null, 1);
}

Я уже прочитал этот вопрос: код ошибки Android SQLite 21 и искал все, что упоминалось там.

SQLiteDatabase (поле db) открывается только один раз и никогда не закрывается непосредственно из кода приложения. Многопоточный доступ не должен быть проблемой, потому что первая вещь в методе executeInsert() — это блокировка базы данных (я проверял исходный код Android 2.1, поэтому я предполагаю, что это поведение не изменилось в 3.1).

Здасти, создал вот такую таблицу:

CREATE TABLE IF NOT EXISTS `test_tab` (
  `system_id` int(5) NOT NULL AUTO_INCREMENT,
  `id` int(4) NOT NULL,
  `name` char(255) DEFAULT NULL,
  `filtered_name` char(255) DEFAULT NULL,
  `real` enum('false','true') DEFAULT NULL,
  `image` char(255) DEFAULT NULL,
  PRIMARY KEY (`system_id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

При добавлении строки таким макаром:

# 2.7
# -*- coding: utf-8 -*-
from mysql.connector import MySQLConnection, Error
data_in_db = {'id': '2', 'name': 'test-test-test', 'filtered_name': 'test', 'real': 'true', 'image': '/images/2.jpg'}
query = "INSERT INTO test_tab(id, name, filtered_name, real, image) " 
							"VALUES(%d, %s, %s, %s, %s)"
args = (data_in_db.get('id'), data_in_db.get('name'), data_in_db.get('filtered_name'), data_in_db.get('real'), data_in_db.get('image'))
	
db_config = {'password': 'root', 'host': 'localhost', 'user': 'root', 'database': 'anime'}	
	
try:
	conn = MySQLConnection(**db_config)
	
	cursor = conn.cursor()
	cursor.execute(query, args)
	if cursor.lastrowid:
		print('last insert id', cursor.lastrowid)
	else:
		print('last insert id not found')
	conn.commit()
			
except Error as error:
	print(error)
	
finally:
	cursor.close()
	conn.close()

выскакивает ошибка «Wrong number of arguments during string formatting«
Что я делаю не так?
Делаю по вот этому примеру: http://www.internet-technologies.ru/articles/article_2190.html
но там не указана структура таблицы

Отредактировано degid (Март 31, 2015 09:00:52)

Иногда я получаю исключение SQLiteMisuseException при вставке строки. Приложение отлично работает на сотнях устройств, но на одном с андроидом 3.1 есть исключение SQLite. Трассировки стека:

    android.database.sqlite.SQLiteMisuseException: error code 21: not an error
    at android.database.sqlite.SQLiteStatement.native_executeInsert(Native Method)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:112)

Это код, который вызывает executeInsert():

    final SQLiteStatement insUrlStmt = db.compileStatement("insert into urls (url,idx) values (?,?)");
    insUrlStmt.bindString(1, url)
    insUrlStmt.bindLong(2, idx);
    return insUrlStmt.executeInsert();

Объявление поля БД:

    private final SQLiteDatabase db;

Инициализация поля db (это вызывается один раз в onCreate() объекта класса Application) и ссылка на DataHelper хранится статически в экземпляре приложения:

    public DataHelper(Context context) {db = new OpenHelper(context).getWritableDatabase();   }

Конструктор OpenHelper:

    protected OpenHelper(Context context) 
{
     super(context, "database.db", null, 1);       
}

Я уже читал этот вопрос: Android SQLite error code 21 и искал упомянутые вещи там.

SQLiteDatabase (поле db) открывается только один раз и никогда не закрывается напрямую из кода приложения. Многопоточный доступ не должен быть проблемой, потому что первое, что в методе executeInsert() — это блокировка базы данных (я проверил исходный код Android 2.1, поэтому я предполагаю, что это поведение не изменилось в 3.1).

2 ответа

Попробуйте использовать ContentValues для вставки записи.

Например:

ContentValues cv = new ContentValues();
cv.put("column1Name", column1Value);
cv.put("column2Name", column2Value);//and so on
db.insert(TABLE_NAME, null, cv);


0

GAMA
24 Апр 2012 в 15:36

Проверьте свои операторы sql — это может быть нулевая или нулевая длина. У меня была такая же проблема при получении операторов sql из класса, которые мне приходилось разбивать всякий раз, когда был найден новый символ строки. Последний оператор содержал символ новой строки, и я попытался выполнить этот оператор после того, который был пуст.


0

Guido Amabili
18 Фев 2016 в 15:10

  • Ошибка вследствие человеческого фактора
  • Ошибка вследствие недоразумения как пишется
  • Ошибка вскоре потребуется регулировка смазочной системы лексус
  • Ошибка вск тойота камри 40
  • Ошибка всех датчиков хендай крета