Sql error unrecognized token

SQL logic error: Unrecognized token: «0x» #875 Comments When attempting to migrate a SQL database to SQLite, I receive the following error: SQLite/SQL Server Compact Toolbox ErrorCode : 1 Message : SQL logic error unrecognized token: «0x» Result : Error Steps to reproduce Connect SQL database in VS Add data connection in SqlCeToolbox Select […]

Содержание

  1. SQL logic error: Unrecognized token: «0x» #875
  2. Comments
  3. Steps to reproduce
  4. Further technical details
  5. Thread: [RESOLVED] How to fix SQL logic error unrecognized token: «@» (VB.NET)
  6. [RESOLVED] How to fix SQL logic error unrecognized token: «@» (VB.NET)
  7. Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)
  8. Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)
  9. Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)
  10. Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)
  11. Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)
  12. Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)
  13. unrecognized token error #1270
  14. Comments
  15. Details for the issue
  16. Useful extra information
  17. I’m opening this issue because:
  18. I’m using DB4S on:
  19. I’m using DB4S version:
  20. I have also:
  21. sqlite3.OperationalError: нераспознанный токен: отметка даты Python «01T00»
  22. 2 ответы

SQL logic error: Unrecognized token: «0x» #875

When attempting to migrate a SQL database to SQLite, I receive the following error:

SQLite/SQL Server Compact Toolbox
ErrorCode : 1
Message : SQL logic error
unrecognized token: «0x»
Result : Error

Steps to reproduce

Connect SQL database in VS
Add data connection in SqlCeToolbox
Select Migrate to SQLite.
Select tables
Select database file name
Status changes to Importing Data
Error occurs and database file is created with zero bytes.

Further technical details

Toolbox/Power Tools version: (found in About dialog — blue questionmark icon)
Version 4.7.670.0 — more than 900,000 downloads

SQL Server Compact 4.0 in GAC — No
SQL Server Compact 4.0 DbProvider — No

SQL Server Compact 4.0 DDEX provider — No
SQL Server Compact 4.0 Simple DDEX provider — Yes

SQL Server Compact 3.5 in GAC — No
SQL Server Compact 3.5 DbProvider — No

SQL Server Compact 3.5 DDEX provider — No

Sync Framework 2.1 SqlCe 3.5 provider — No

SQLite ADO.NET Provider included: 1.0.109.0
SQLite EF6 DbProvider in GAC — No
System.Data.SQLite DDEX provider — No
SQLite Simple DDEX provider — Yes

Database engine:
SQL Server

Visual Studio or SSMS version:
Visual Studio Enterprise 2019 16.8.1

The text was updated successfully, but these errors were encountered:

Источник

Thread: [RESOLVED] How to fix SQL logic error unrecognized token: «@» (VB.NET)

Thread Tools
Display

[RESOLVED] How to fix SQL logic error unrecognized token: «@» (VB.NET)

I switched my solution (in VB.NET) from working with SQL .mdf database to SQLite .db database. most of the program works fine, but this particular INSERT query is nor working, in fact it is not INSERTING anything to the table, instead it throws this error:

I’ve already check my code, and my table and still don’t see why this happens, I added a watch to many lines, and all I can see is the variable ex getting the exception value of: SQL logic error unrecognized token: «@» right after the agregar.ExecuteNonQuery() command.

This is my code:

This was my table definition when I was using SQL .mdf database and this used to work fine.

This is my table definition now that I’m using SQLite .db database:

BTW how do I specify a table row that was type money?, since that option is not available in SQLite, so I used numeric type for «Importe» row.

Last edited by Spybot; May 7th, 2019 at 12:11 AM .

Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

I haven’t really used SQLite but I was under the impression that the ADO.NET provider supported «@» as a parameter prefix. I have also seen people use «$», so try that. If that doesn’t work, try not using names at all in the SQL code and just using «?» for each parameter.

Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

Again, I don’t use SQLite but I do know how to use a search engine:

You can use DECIMAL or NUMERIC and both will produce a type affinity of NUMERIC.

Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

Yes, «$» didn’t work. but «?» did. now it is INSERTING all the records into the table, but on the: «Importe» row it inserts $0.00 which is not the correct value on the datagridview, for example the datagridview shows $50.00 but the value that is saved in the table is $0.00

Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

Don’t use a loop to save data from a DataGridView in the first place. Create a DataTable with the appropriate schema and bind it to the grid first. You can then save all the data to the database with a single call to the Update method of a data adapter.

Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

I tried DECIMAL and NUMERIC and they didn’t work. but I saw your post #3 (thanks for the link) and I found that. since my DataGridView shows «$» so it is considered as TEXT affinity, then I went to my table and changed my «Importe» row to TEXT affinity and now it works as expected.

I appreciate your help very much!

Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

I tried DECIMAL and NUMERIC and they didn’t work. but I saw your post #3 (thanks for the link) and I found that. since my DataGridView shows «$» so it is considered as TEXT affinity, then I went to my table and changed my «Importe» row to TEXT affinity and now it works as expected.

I appreciate your help very much!

That’s part of the problem. You should not be saving that currency symbol to the database. Currency values are numbers and should be stored as numbers. If you use a DataTable then you can specify the data type for the corresponding DataColumn to be Decimal and then you can configure the grid to format the numbers in the data source as currency. Thinks like currency formatting should be a UI job only. No data should be stored as text if there is a more appropriate option.

Источник

unrecognized token error #1270

Details for the issue

Selecting values in double quotes containing double hyphen substring returns «unrecognized token» error.

Please see example below.
—Error unrecognized token:
select «anything—something»

—no error
select ‘anything—something’

I’m opening this issue because:

  • DB4S is crashing
  • DB4S has a bug
  • DB4S needs a feature
  • DB4S has another problem

I’m using DB4S on:

  • Windows: ( version: ___ )
  • Linux: ( _distro:Ubuntu )
  • Mac OS: ( version: ___ )
  • Other: ___

I’m using DB4S version:

I have also:

  • Tried out the latest nightly version: https://github.com/sqlitebrowser/sqlitebrowser#nightly-builds
  • Searched for an existing similar issue: https://github.com/sqlitebrowser/sqlitebrowser/issues?utf8=%E2%9C%93&q=is%3Aissue%20

The text was updated successfully, but these errors were encountered:

Ouch, that definitely sounds like a bug. Have you tried any of the commits prior to that, to see if that’s the one which introduces it?

The same error with version 3.10.99 from 2017-12-09, I see on my system. Thank you for looking into it.

Oops. Just realised something that should have been obvious to me right away before.

This is probably not a bug after all. With SQL, the single and double quote characters aren’t the same thing.

  • Single quote characters ‘ are used to start and end strings. eg:
  • Double quote characters » are used to start and end identifiers (such as field names). eg:

In the above example, the table bar contains a field called my field with spaces in its name .

Further reference info, in case it’s useful:

With your double quote example, the «unrecognized token» message is probably meaning that it’s looking for a field called (literally) «anything—something», and not finding it. 😉

Thank you for pointing to SQLite documentation.
I have bumped into this while operating with strings already containing single quotes.
It seems that official sqlite3 command line tool does not produce «unrecognized token» error.
Thanks anyway.

Hmmm, yeah you’re right. I’ve just tried it here with the sqlite3 client (and older version, 3.7.17 on my CentOS 7 desktop), and a recent build of DB4S.

It looks like DB4S is getting misunderstanding the double quotes. For example, with this (from above):

In the sqlite3 CLI it works, adding a new row into the table bar . DB4S gives this error instead:

Looking at that error message, there’s an extra » at the start of the TEXT2 string. Guessing here, but this looks like we’re somehow getting the quotes wrong after all.

So. yep this does seem like a bug. Our Execute SQL tab should accept anything that the SQLite CLI does. Thanks for being persistent. 😀

Источник

sqlite3.OperationalError: нераспознанный токен: отметка даты Python «01T00»

У меня возникла проблема со вставкой значений в базу данных SQLite. Данные я загружаю с сайта норвежского парламента data.stortinget.no. Я получаю сообщение об ошибке: sqlite3.OperationalError: нераспознанный токен: «01T00»

Вот метод, в котором возникает ошибка: (я знаю об ошибке отступа в этом отрывке)

Сообщение, напечатанное печатью чуть выше cur.execute: id: 2009-2013 fra: 2009-10-01T00:00:00 til: 2013-09-30T23:59:59 Вся трассировка ошибки:

Я обратился к руководству по SQLite, и кажется, что формат поддерживается, поэтому мне интересно, откуда возникла проблема.

задан 22 июн ’12, 17:06

Вы не передаете дату с кавычками INSERT INTO perioder(fra, id, til) VALUES(‘%s’,%s,’%s’) ? — Jones

То, что вы вставляете, VALUES(2009-2013, 2009-10-01T00:00:00, 2013-09-30T23:59:59) . Вы понимаете, почему это неправильно, верно? Вы только что вставили эквивалент VALUES(-4, -1-01T00:00:00, 2004-30T23:59:59) , что явно является синтаксической ошибкой, поскольку 01T00 нельзя вычесть из -1 . Просто используйте execute правильно вместо интерполяции строк. — Francis Avila

Я вижу это сейчас. Я думал, что %s добавил нужные кавычки, но ошибся. Спасибо вам обоим за помощь, теперь все работает. Другая проблема возникла, когда я запустил код. Он выполняет первый метод, но не добавляет данные из дополнительного. Могу ли я передать курсор методам и добавить данные, или мне нужно больше курсоров? (Программа не имеет параллелизма) — olovholm

2 ответы

Правильный способ — использовать параметризованный запрос.
Пример:

Для каждого драйвера базы данных существует определенный параметр «стиль».
В случае SQLite этот стиль параметра ? .

Также обратите внимание, что значения параметров передаются в качестве второго аргумента в execute() .
Использование строковой интерполяции оставляет вас уязвимым для всех видов проблем с цитированием (например, той, что привела вас сюда) и возможности атаки путем внедрения SQL.

Для получения дополнительной информации прочтите DB-API и вики по программированию баз данных.

Есть ли лучший способ сделать это, если таблица, в которую я вставляю, имеет много полей (намного больше 3)? — Г-н Шикаданс

Конечно. У вас нет таких имен столбцов. Этот синтаксис также допустим: INSERT INTO your_table VALUES (. . ); . И вы можете динамически генерировать заполнители параметров. Пожалуйста, посмотрите этот ответ stackoverflow.com/a/2253879/42346 для получения информации об этом втором шаге. — механическое_ мясо

Если вы хотите сохранить метки даты в виде строк ( TEXT ) в SQLite, я рекомендую отформатировать текст, который вы хотите выполнить, следующим образом:

SQLite возвращает ошибки, если вставляемые вами значения не имеют кавычек. Форматирование текста с помощью »%s» вместо %s вставит строковое значение с кавычками в отформатированную строку:

Источник

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • VS 2019 [RESOLVED] How to fix SQL logic error unrecognized token: «@» (VB.NET)

  1. May 7th, 2019, 12:08 AM


    #1

    Spybot is offline

    Thread Starter


    Hyperactive Member

    Spybot's Avatar


    Resolved [RESOLVED] How to fix SQL logic error unrecognized token: «@» (VB.NET)

    Hello!

    I switched my solution (in VB.NET) from working with SQL .mdf database to SQLite .db database. most of the program works fine, but this particular INSERT query is nor working, in fact it is not INSERTING anything to the table, instead it throws this error:
    Name:  Error.png
Views: 5190
Size:  9.3 KB

    I’ve already check my code, and my table and still don’t see why this happens, I added a watch to many lines, and all I can see is the variable ex getting the exception value of: SQL logic error unrecognized token: «@» right after the agregar.ExecuteNonQuery() command.

    This is my code:

    VB.NET Code:

    1. Public Sub Save_to_Ventas_del_Dia_Table()

    2.         Dim Conexion As SQLiteConnection = New SQLiteConnection("Data Source=C:SystemWinDB2Owner.db;Version=3;")

    3.         Dim agregar As SQLiteCommand = New SQLiteCommand("INSERT INTO Ventas_del_Dia_Table VALUES (@#_de_Cliente, @Nombre_Cliente, @Concepto, @Precio_Unitario, @Cantidad, @Descuento, @Importe, @Fecha, @Entradas, @Salidas, @Motivo_de_la_Salida, @Realizado_Por)", Conexion)

    4.         If (Conexion.State = ConnectionState.Closed) Then Conexion.Open()

    5.         Dim fila As DataGridViewRow = New DataGridViewRow()

    6.         Try

    7.             For Each fila In Main_Program.DataGridView1.Rows

    8.                 agregar.Parameters.Clear()

    9.                 agregar.Parameters.AddWithValue("@#_de_Cliente", Convert.ToString(fila.Cells(0).Value))

    10.                 agregar.Parameters.AddWithValue("@Nombre_Cliente", Convert.ToString(fila.Cells(1).Value))

    11.                 agregar.Parameters.AddWithValue("@Concepto", Convert.ToString(fila.Cells(2).Value))

    12.                 agregar.Parameters.AddWithValue("@Precio_Unitario", Convert.ToString(fila.Cells(3).Value))

    13.                 agregar.Parameters.AddWithValue("@Cantidad", Convert.ToString(fila.Cells(4).Value))

    14.                 agregar.Parameters.AddWithValue("@Descuento", Convert.ToString(fila.Cells(5).Value))

    15.                 agregar.Parameters.AddWithValue("@Importe", Convert.ToString(fila.Cells(6).Value))

    16.                 agregar.Parameters.AddWithValue("@Fecha", Convert.ToString(fila.Cells(8).Value))

    17.                 agregar.Parameters.AddWithValue("@Entradas", "No aplica")

    18.                 agregar.Parameters.AddWithValue("@Salidas", "No aplica")

    19.                 agregar.Parameters.AddWithValue("@Motivo_de_la_Salida", "No aplica")

    20.                 agregar.Parameters.AddWithValue("@Realizado_Por", Convert.ToString(fila.Cells(9).Value))

    21.                 agregar.ExecuteNonQuery()

    22.             Next

    23.         Catch ex As Exception

    24.             MsgBox(ex.Message)

    25.         End Try

    26.     End Sub

    This was my table definition when I was using SQL .mdf database and this used to work fine.

    VB.NET Code:

    1. CREATE TABLE [dbo].[Ventas_del_Dia_Table] (

    2.     [#_de_Cliente]        NVARCHAR (10)  NULL,

    3.     [Nombre_Cliente]      NVARCHAR (150) NULL,

    4.     [Concepto]            NVARCHAR (200) NULL,

    5.     [Precio_Unitario]     NVARCHAR (10)  NULL,

    6.     [Cantidad]            NVARCHAR (10)  NULL,

    7.     [Descuento]           NVARCHAR (10)  NULL,

    8.     [Importe]             MONEY          NULL,

    9.     [Fecha]               NVARCHAR (30)  NULL,

    10.     [Entradas]            NVARCHAR (50)  NULL,

    11.     [Salidas]             NVARCHAR (50)  NULL,

    12.     [Motivo_de_la_Salida] VARCHAR (MAX)  NULL,

    13.     [Realizado_Por]       NVARCHAR (50)  NULL

    14. );

    This is my table definition now that I’m using SQLite .db database:

    VB.NET Code:

    1. CREATE TABLE CREATE TABLE "Ventas_del_Dia_Table" (

    2.     "#_de_Cliente"        TEXT,

    3.     "Nombre_Cliente"      TEXT,

    4.     "Concepto"        TEXT,

    5.     "Precio_Unitario"     TEXT,

    6.     "Cantidad"        TEXT,

    7.     "Descuento"       TEXT,

    8.     "Importe"         NUMERIC,

    9.     "Fecha"               TEXT,

    10.     "Entradas"        TEXT,

    11.     "Salidas"         TEXT,

    12.     "Motivo_de_la_Salida" TEXT,

    13.     "Realizado_Por"       TEXT

    14. );

    BTW how do I specify a table row that was type money?, since that option is not available in SQLite, so I used numeric type for «Importe» row.

    Thank you.

    Last edited by Spybot; May 7th, 2019 at 12:11 AM.


  2. May 7th, 2019, 12:27 AM


    #2

    Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

    I haven’t really used SQLite but I was under the impression that the ADO.NET provider supported «@» as a parameter prefix. I have also seen people use «$», so try that. If that doesn’t work, try not using names at all in the SQL code and just using «?» for each parameter.


  3. May 7th, 2019, 12:37 AM


    #3

    Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

    Again, I don’t use SQLite but I do know how to use a search engine:

    https://www.sqlite.org/datatype3.html

    You can use DECIMAL or NUMERIC and both will produce a type affinity of NUMERIC.


  4. May 7th, 2019, 01:02 AM


    #4

    Spybot is offline

    Thread Starter


    Hyperactive Member

    Spybot's Avatar


    Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

    Hi jmcilhinney!

    Yes, «$» didn’t work… but «?» did. now it is INSERTING all the records into the table, but on the: «Importe» row it inserts $0.00 which is not the correct value on the datagridview, for example the datagridview shows $50.00 but the value that is saved in the table is $0.00


  5. May 7th, 2019, 01:13 AM


    #5

    Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

    Don’t use a loop to save data from a DataGridView in the first place. Create a DataTable with the appropriate schema and bind it to the grid first. You can then save all the data to the database with a single call to the Update method of a data adapter.


  6. May 7th, 2019, 01:34 AM


    #6

    Spybot is offline

    Thread Starter


    Hyperactive Member

    Spybot's Avatar


    Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

    I tried DECIMAL and NUMERIC and they didn’t work… but I saw your post #3 (thanks for the link) and I found that… since my DataGridView shows «$» so it is considered as TEXT affinity, then I went to my table and changed my «Importe» row to TEXT affinity and now it works as expected.

    I appreciate your help very much!


  7. May 7th, 2019, 01:44 AM


    #7

    Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

    Quote Originally Posted by Spybot
    View Post

    I tried DECIMAL and NUMERIC and they didn’t work… but I saw your post #3 (thanks for the link) and I found that… since my DataGridView shows «$» so it is considered as TEXT affinity, then I went to my table and changed my «Importe» row to TEXT affinity and now it works as expected.

    I appreciate your help very much!

    That’s part of the problem. You should not be saving that currency symbol to the database. Currency values are numbers and should be stored as numbers. If you use a DataTable then you can specify the data type for the corresponding DataColumn to be Decimal and then you can configure the grid to format the numbers in the data source as currency. Thinks like currency formatting should be a UI job only. No data should be stored as text if there is a more appropriate option.


  8. May 7th, 2019, 08:46 AM


    #8

    Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

    Quote Originally Posted by jmcilhinney
    View Post

    That’s part of the problem. You should not be saving that currency symbol to the database. Currency values are numbers and should be stored as numbers.

    +100!

    I guess I should have mentioned some of the oddities of SQLite when recommending it in the other thread. Another important one is there is no date or time data types as noted in section 2.2 of the link above so you need to decide which of the 3 formats you want to use. I personally use ISO8601 strings since it’s easiest when looking at the raw data.

    Additionally, if you are doing a lot of inserts at once (bulk loading) on a spinning hard drive especially, wrap them in a transaction (possibly in blocks if more then several thousand) or it will be pretty slow.


  9. May 7th, 2019, 10:35 AM


    #9

    Spybot is offline

    Thread Starter


    Hyperactive Member

    Spybot's Avatar


    Re: How to fix SQL logic error unrecognized token: «@» (VB.NET)

    Hi!

    Well… I think you’re right, I shouldn’t save the currency symbol to the database, I also agree that currency formatting should be for UI purposes only, I’ll fix that!

    Thanks for the suggestion.


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • VS 2019 [RESOLVED] How to fix SQL logic error unrecognized token: «@» (VB.NET)


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Содержание

  1. unrecognized token error #1270
  2. Comments
  3. isrep commented Dec 15, 2017
  4. Details for the issue
  5. Useful extra information
  6. I’m opening this issue because:
  7. I’m using DB4S on:
  8. I’m using DB4S version:
  9. I have also:
  10. justinclift commented Dec 15, 2017
  11. isrep commented Dec 16, 2017
  12. justinclift commented Dec 16, 2017 •
  13. isrep commented Dec 16, 2017
  14. justinclift commented Dec 16, 2017
  15. sqlite 3 OperationalError: unrecognized token #4757
  16. Comments
  17. ichorid commented Aug 16, 2019
  18. ichorid commented Aug 16, 2019
  19. qstokkink commented Aug 17, 2019 •
  20. grimadas commented Aug 20, 2019
  21. ichorid commented Sep 14, 2019
  22. ichorid commented Sep 14, 2019
  23. devos50 commented Sep 14, 2019 •

unrecognized token error #1270

Details for the issue

Selecting values in double quotes containing double hyphen substring returns «unrecognized token» error.

Please see example below.
—Error unrecognized token:
select «anything—something»

—no error
select ‘anything—something’

I’m opening this issue because:

  • DB4S is crashing
  • DB4S has a bug
  • DB4S needs a feature
  • DB4S has another problem

I’m using DB4S on:

  • Windows: ( version: ___ )
  • Linux: ( _distro:Ubuntu )
  • Mac OS: ( version: ___ )
  • Other: ___

I’m using DB4S version:

I have also:

  • Tried out the latest nightly version: https://github.com/sqlitebrowser/sqlitebrowser#nightly-builds
  • Searched for an existing similar issue: https://github.com/sqlitebrowser/sqlitebrowser/issues?utf8=%E2%9C%93&q=is%3Aissue%20

The text was updated successfully, but these errors were encountered:

Ouch, that definitely sounds like a bug. Have you tried any of the commits prior to that, to see if that’s the one which introduces it?

The same error with version 3.10.99 from 2017-12-09, I see on my system. Thank you for looking into it.

Oops. Just realised something that should have been obvious to me right away before.

This is probably not a bug after all. With SQL, the single and double quote characters aren’t the same thing.

  • Single quote characters ‘ are used to start and end strings. eg:
  • Double quote characters » are used to start and end identifiers (such as field names). eg:

In the above example, the table bar contains a field called my field with spaces in its name .

Further reference info, in case it’s useful:

With your double quote example, the «unrecognized token» message is probably meaning that it’s looking for a field called (literally) «anything—something», and not finding it. 😉

Thank you for pointing to SQLite documentation.
I have bumped into this while operating with strings already containing single quotes.
It seems that official sqlite3 command line tool does not produce «unrecognized token» error.
Thanks anyway.

Hmmm, yeah you’re right. I’ve just tried it here with the sqlite3 client (and older version, 3.7.17 on my CentOS 7 desktop), and a recent build of DB4S.

It looks like DB4S is getting misunderstanding the double quotes. For example, with this (from above):

In the sqlite3 CLI it works, adding a new row into the table bar . DB4S gives this error instead:

Looking at that error message, there’s an extra » at the start of the TEXT2 string. Guessing here, but this looks like we’re somehow getting the quotes wrong after all.

So. yep this does seem like a bug. Our Execute SQL tab should accept anything that the SQLite CLI does. Thanks for being persistent. 😀

Источник

sqlite 3 OperationalError: unrecognized token #4757

v7.3-RC2.
Happens every 2nd attempt to run Tribler both on Windows and on Linux at the end of the GUI bootup.

The text was updated successfully, but these errors were encountered:

@qstokkink , please look at this.

This happens when you feed a bad query to the database (see https://stackoverflow.com/a/11160750). Though the stacktrace is very limited, it seems to be crashing on the bootstrap file script:

Lines 541 to 548 in 54a2d62

if self . bootstrap and not self . bootstrap . bootstrap_finished and hexlify (
infohash ) == self . session . config . get_bootstrap_infohash () and self . trustchain_community :
self . bootstrap . bootstrap_finished = True
with open ( self . bootstrap . bootstrap_file , ‘r’ ) as f :
sql_dumb = text_type ( f . read ())
self . _logger . info ( «Executing script for trustchain bootstrap» )
self . trustchain_community . persistence . executescript ( sql_dumb )
self . trustchain_community . persistence . commit ()

As I can’t reproduce this, I’ll unassign myself. Passing this to the original author @grimadas.

I couldn’t reproduce it. Let me know if you see it again

It is still there. An it is the most frequent error in the reporter. It has three different forms:
17 traces:

If our reporter does not lie, and this thing still happens, it accounts for at least 20% of all reported traces. It should be assessed immediately with a hotfix release.

Out of the 124 stack traces reported for 7.3.0, 25 are related to this unrecognized token error, so thanks for pointing this out! They are both reported by Windows (32 and 64 bit) and Linux users. This error seems to happen in the sesscb_states_callback method, which is AFAIK, the only method in Tribler that is still invoked on the threadpool. This is also visible in the stack traces.

This method should, like most other methods, be scheduled on the reactor thread and this change is trivial to implement (I will try to do so tomorrow). I’m not sure why we haven’t done this yet, probably because it was not raising any problem up to this point.

Preparing a hotfix release at this point might be a bit hard, since we upgraded the OS of our (builder) Mac machine. There are some pending issues with PyInstaller (addressed in #4837).

Источник

Михалыч

687 / 293 / 54

Регистрация: 28.02.2013

Сообщений: 838

1

01.08.2020, 15:17. Показов 11334. Ответов 4

Метки нет (Все метки)


Добрый день! У меня есть база данных:

Python
1
2
3
            cursorObj.execute("""CREATE TABLE objects(id INTEGER PRIMARY KEY, data TEXT NOT NULL,
                                                                 photo BLOB NOT NULL, name_photo TEXT NOT NULL,
                                                                 scale_photo TEXT NOT NULL)""")

Я хочу в data записать значения словаря приведенного к str:

Python
1
2
3
                sql = 'UPDATE objects SET data = "' + str(self.data_obj) + '" where id = ' + str(row[0])
                cursorObj.execute(sql)
                sqliteConnection.commit()

И вот когда мой словарь self.data_obj содержит обычный словарь «ключ-значение» то все нормально, а вот когда в значениях появляются вложенные словари он выдает ошибку

sqlite3.OperationalError: unrecognized token: «{«



0



0x10

3254 / 2056 / 351

Регистрация: 24.11.2012

Сообщений: 4,909

01.08.2020, 16:02

2

Лучший ответ Сообщение было отмечено Михалыч как решение

Решение

Нельзя же собирать запрос конкатенацией строк.

Usually your SQL operations will need to use values from Python variables. You shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack (see https://xkcd.com/327/ for humorous example of what can go wrong).

Instead, use the DB-API’s parameter substitution.
[…]

Python
1
2
3
4
5
6
7
8
9
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
 
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())
[...]

https://docs.python.org/3/library/sqlite3.html



1



Михалыч

687 / 293 / 54

Регистрация: 28.02.2013

Сообщений: 838

02.08.2020, 09:29

 [ТС]

3

Цитата
Сообщение от 0x10
Посмотреть сообщение

Нельзя же собирать запрос конкатенацией строк.

До этого работало) Я же правильно понимаю, что если 2 переменные то должно быть 2 знака вопроса (под рукой пока той программы нет, а то бы давно попробовал, а любопытство распирает), т.е. примерно так:

Python
1
2
3
data = str(self.data_obj) 
tmp_id = str(row[0])
cursorObj.execute('UPDATE objects SET data = ? where id = ?', data, tmp_id)



0



3254 / 2056 / 351

Регистрация: 24.11.2012

Сообщений: 4,909

02.08.2020, 09:32

4

Цитата
Сообщение от Михалыч
Посмотреть сообщение

Я же правильно понимаю, что если 2 переменные то должно быть 2 знака вопроса

Да, только execute принимает два аргумента: строку и кортеж.



1



687 / 293 / 54

Регистрация: 28.02.2013

Сообщений: 838

02.08.2020, 09:38

 [ТС]

5

0x10, Спасибо



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

02.08.2020, 09:38

Помогаю со студенческими работами здесь

Ошибка при разборе запроса. [ Token line number = 1,Token line offset = 26,Token in error = Наименование ]
Доброго времени суток, никак не пойму в чем проблема.
using System;
using…

Как правильно записать данные в Json
Доброго времени суток, возникла такая проблема.

Имеется массив объектов типа:

dataDocument…

Как правильно записать данные в List?
Пишу программу для создания тестов.
Первый класс

class Answer
{
public String…

Как правильно записать данные в файл PHP
Доброе утро. При попытке записать данные в файл, у меня в файл записывается сначала имя, а потом…

Как правильно записать данные из StringBuilder в combobox?
comboBox2.Items.Add(sb);
Если писать так то все что есть в StringBuilder sb будет записано в одну…

Как правильно записать данные в массив файла
Добрый вечер!
Пишу программу работы с файлами(то есть создать, открыть, сохранить, заполнить,…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

5

Статус темы:

Закрыта.
  1. При сохранении количества вопросов выдает ошибку:
    Когда захожу в систему хелпером он нормально все сохраняет ;/

    [14:21:41 WARN]: org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (unrecognized token: "'1af87e5f-3ef2-31a4-8b8a-4cd0628bb8ae''")
    [14:21:41 WARN]:        at org.sqlite.core.DB.newSQLException(DB.java:909)
    [14:21:41 WARN]:        at org.sqlite.core.DB.newSQLException(DB.java:921)
    [14:21:41 WARN]:        at org.sqlite.core.DB.throwex(DB.java:886)
    [14:21:41 WARN]:        at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
    [14:21:41 WARN]:        at org.sqlite.core.NativeDB.prepare(NativeDB.java:127)
    [14:21:41 WARN]:        at org.sqlite.core.DB.prepare(DB.java:227)
    [14:21:41 WARN]:        at org.sqlite.jdbc3.JDBC3Statement.executeQuery(JDBC3Statement.java:81)
    [14:21:41 WARN]:        at ru.solomka.database.MySQLDataBase.saveQuestion(MySQLDataBase.java:153)
    [14:21:41 WARN]:        at ru.solomka.commands.handler.QuestionSendHandler$Send.lambda$new$0(QuestionSendHandler.java:141)
    [14:21:41 WARN]:        at ru.solomka.commands.handler.QuestionSendHandler$Send$$Lambda$11/922419138.execute(Unknown Source)
    [14:21:41 WARN]:        at ru.solomka.OptionalCommand.basic.BasicCommand.use(BasicCommand.java:33)
    [14:21:41 WARN]:        at ru.solomka.OptionalCommand.basic.BasicCommandHandler.onCommand(BasicCommandHandler.java:47)
    [14:21:41 WARN]:        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44)
    [14:21:41 WARN]:        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141)
    [14:21:41 WARN]:        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.dispatchCommand(CraftServer.java:648)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.PlayerConnection.handleCommand(PlayerConnection.java:1399)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.PlayerConnection.a(PlayerConnection.java:1234)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.PacketPlayInChat.a(PacketPlayInChat.java:45)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.PacketPlayInChat.a(PacketPlayInChat.java:1)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.PlayerConnectionUtils$1.run(SourceFile:13)
    [14:21:41 WARN]:        at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    [14:21:41 WARN]:        at java.util.concurrent.FutureTask.run(Unknown Source)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.SystemUtils.a(SourceFile:46)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.D(MinecraftServer.java:748)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.DedicatedServer.D(DedicatedServer.java:406)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.C(MinecraftServer.java:679)
    [14:21:41 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:577)
    [14:21:41 WARN]:        at java.lang.Thread.run(Unknown Source)

    Использование в классе:

                  
    
    
    Player p = (Player) sender;
    
    UUID sender_uuid = p.getUniqueId();
    
       if (sender.hasPermission(getPermission()) || sender.isOp()) {
    
            if (!map.contains(sender_uuid)) {
                map.add(sender_uuid);
            }
    
            if (map.contains(sender_uuid)) {
                if (join.isEmpty()) {
                    send(sender, translateAlternateColorCodes('&', getString("NoHelpers")));
                    return;
                }
    
                if(haveBan.containsKey(sender_uuid)){
                    map.remove(sender_uuid);
                    send(sender, translateAlternateColorCodes('&', "&c&l[ERROR] &fВы в &cвременном бане&f! &fЕсли вы не согласны c &cбаном&f - напишите &cжалобу&f!"));
                    return;
                }
    
                if (!haveQuestion.containsKey(sender_uuid)) {
                    MySQL.saveQuestion(MySQL.getQuestion(sender_uuid) + 1, sender_uuid);
                    for (UUID uuid : join) {
                        Bukkit.getPlayer(uuid).sendMessage(translateAlternateColorCodes('&', "&6[НОВЫЙ ВОПРОС] &fВопрос: &c" + sb.toString() + "&8&l‖ &fИгрок: &9" + sender.getName()));
                        haveQuestion.put(sender_uuid, true);
                    }
                    send(sender, translateAlternateColorCodes('&', getString("WaitAnswer")));
                    return;
                }
                if(map.contains(sender_uuid)) {
                    if (haveQuestion.containsKey(sender_uuid)) {
                        send(sender, translateAlternateColorCodes('&', getString("HaveQuestion")));
                        return;
                    }
                }
                return;
            }
        }
        send(sender, translateAlternateColorCodes('&', getString("NotHavePermission")));
    };
    

    База данных:

        public static void saveDat(List<Data> log) {
            try {
    
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                for (Data dat : log) {
                    statement.executeUpdate(String.format("INSERT player_data ('UUID', 'numAnswer', 'numQuestion', 'numJoin', 'numBan') VALUES (%d, '%s', '%s', '%s', '%s', '%s');",
                            dat.getId(), dat.getAnswer(), dat.getQuestion(), dat.getJoin(), dat.getBan()));
                }
                statement.close();
                c.close();
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static int saveJoin(int join, UUID id) {
            try {
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                ResultSet resultSet = statement.executeQuery(String.format("SELECT 'numJoin', 'UUID' FROM player_data WHERE numJoin ='%s' and UUID ='%s''", id, join));
    
                while (resultSet.next()){
    
                    join(resultSet.getInt("numJoin"));
                    uuid((UUID) resultSet.getObject("UUID"));
                }
    
                statement.close();
                c.close();
    
            } catch (Exception e){
                e.printStackTrace();
            }
            return join;
        }
    
        public static int saveAnswer(int answer, UUID id) {
            try {
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                ResultSet resultSet = statement.executeQuery(String.format("SELECT 'numAnswer', 'UUID' FROM player_data WHERE numAnswer ='%s' and UUID ='%s''", answer, id));
    
                while (resultSet.next()){
                    answer(resultSet.getInt("numAnswer"));
                    uuid((UUID) resultSet.getObject("UUID"));
                }
    
                statement.close();
                c.close();
    
            } catch (Exception e){
                e.printStackTrace();
            }
            return answer;
        }
    
        public static int saveBan(int ban, UUID id) {
            try {
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                ResultSet resultSet = statement.executeQuery(String.format("SELECT 'numBan', 'UUID' FROM player_data WHERE numBan ='%s' and UUID ='%s''", ban, id));
    
                while (resultSet.next()){
                    ban(resultSet.getInt("numBan"));
                    uuid((UUID) resultSet.getObject("UUID"));
                }
    
                statement.close();
                c.close();
    
            } catch (Exception e){
                e.printStackTrace();
            }
            return ban;
        }
    
        public static int saveQuestion(int question, UUID id) {
            try {
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                ResultSet resultSet = statement.executeQuery(String.format("SELECT 'numQuestion', 'UUID' FROM player_data WHERE numQuestion ='%s' and UUID ='%s''", question, id));
    
                while (resultSet.next()){
                    question(resultSet.getInt("numQuestion"));
                    uuid((UUID) resultSet.getObject("UUID"));
                }
    
                statement.close();
                c.close();
    
            } catch (Exception e){
                e.printStackTrace();
            }
            return question;
        }
    
        public static int getJoin(UUID id){
            int i = 0;
            try {
    
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                i = statement.executeUpdate(String.format("SELECT 'numJoin', 'UUID' FROM player_data WHERE numJoin ='%s' and UUID ='%s'", id));
    
                statement.close();
    
                c.close();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return i;
        }
    
        public static int getAnswer(UUID id){
            int i = 0;
            try {
    
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                i = statement.executeUpdate(String.format("SELECT 'numAnswer', 'UUID' FROM player_data WHERE numAnswer ='%s' and UUID ='%s'", id));
    
                statement.close();
    
                c.close();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return i;
        }
    
        public static int getQuestion(UUID id){
            int i = 0;
            try {
    
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                i = statement.executeUpdate(String.format("SELECT 'numQuestion', 'UUID' FROM player_data WHERE numQuestion ='%s' and UUID ='%s'", id));
    
                statement.close();
    
                c.close();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return i;
        }
    
        public static int getBan(UUID id) {
            int i = 0;
            try {
    
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                i = statement.executeUpdate(String.format("SELECT 'numQuestion', 'UUID' FROM player_data WHERE numQuestion ='%s' and UUID ='%s'", id));
    
                statement.close();
    
                c.close();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return i;
        }
  2. Быстрая раскрутка сервера Minecraft


  3. imDaniX

    imDaniX
    Активный участник
    Пользователь

    Баллы:
    96
    Имя в Minecraft:
    imDaniX

  4. Жалуется на формат:

    176 строка

    i = statement.executeUpdate(String.format("SELECT 'numJoin', 'UUID' FROM player_data WHERE numJoin ='%s' AND UUID ='%s'", id));

    ошибкa:

    [14:44:40 INFO]: Solomki issued server command: /JOIN
    [14:44:40 WARN]: java.util.MissingFormatArgumentException: Format specifier '%s'
    [14:44:40 WARN]:        at java.util.Formatter.format(Unknown Source)
    [14:44:40 WARN]:        at java.util.Formatter.format(Unknown Source)
    [14:44:40 WARN]:        at java.lang.String.format(Unknown Source)
    [14:44:40 WARN]:        at ru.solomka.database.MySQLDataBase.getJoin(MySQLDataBase.java:176)
    [14:44:40 WARN]:        at ru.solomka.commands.handler.JoinHandler$Join.lambda$new$0(JoinHandler.java:93)
    [14:44:40 WARN]:        at ru.solomka.commands.handler.JoinHandler$Join$$Lambda$25/843206520.execute(Unknown Source)
    [14:44:40 WARN]:        at ru.solomka.OptionalCommand.basic.BasicCommand.use(BasicCommand.java:33)
    [14:44:40 WARN]:        at ru.solomka.OptionalCommand.basic.BasicCommandHandler.onCommand(BasicCommandHandler.java:47)
    [14:44:40 WARN]:        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44)
    [14:44:40 WARN]:        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141)
    [14:44:40 WARN]:        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.dispatchCommand(CraftServer.java:648)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.PlayerConnection.handleCommand(PlayerConnection.java:1399)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.PlayerConnection.a(PlayerConnection.java:1234)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.PacketPlayInChat.a(PacketPlayInChat.java:45)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.PacketPlayInChat.a(PacketPlayInChat.java:1)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.PlayerConnectionUtils$1.run(SourceFile:13)
    [14:44:40 WARN]:        at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    [14:44:40 WARN]:        at java.util.concurrent.FutureTask.run(Unknown Source)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.SystemUtils.a(SourceFile:46)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.D(MinecraftServer.java:748)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.DedicatedServer.D(DedicatedServer.java:406)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.C(MinecraftServer.java:679)
    [14:44:40 WARN]:        at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:577)
    [14:44:40 WARN]:        at java.lang.Thread.run(Unknown Source)

  5. imDaniX

    imDaniX
    Активный участник
    Пользователь

    Баллы:
    96
    Имя в Minecraft:
    imDaniX

    Не понимаю, зачем ты здесь вообще используешь формат, ну да ладно. В строке два аргумента, а ты используешь лишь один — id.

  6. Так мне нужно получить все значения по этому uuid, если можно по-другому, то как?


  7. imDaniX

    imDaniX
    Активный участник
    Пользователь

    Баллы:
    96
    Имя в Minecraft:
    imDaniX

    Просто не проверяй numJoin =’%s’, наверно?

  8. Вопрос, а почему он игнорирует + 1?

    saveJoin(getJoin(id) + 1, id);

    Выводит в консоль:

    [16:02:11 INFO]: [HelperMode] Игрок вошел — 0

    Что я делаю не так?

  9. Или я что-то не так в методе сохраняю?


  10. imDaniX

    imDaniX
    Активный участник
    Пользователь

    Баллы:
    96
    Имя в Minecraft:
    imDaniX

    Я у тебя вообще не вижу, чтоб ты сохранял какие-либо данные. Впрочем, в saveJoin у тебя явно есть ошибка.

    ResultSet resultSet = statement.executeQuery(String.format("SELECT 'numJoin', 'UUID' FROM player_data WHERE numJoin ='%s' and UUID ='%s''", id, join));

    Здесь ты пытаешься получить количество заходом с условием на количество и uuid — это не имеет никакого смысла, к тому же ты перепутал местами их. Убери проверку количества и переменную join в конце.

  11. Все равно выводит число 0

    saveJoin:

        public static void saveJoin(UUID id) {
            try {
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                ResultSet resultSet = statement.executeQuery(String.format("SELECT 'numJoin', 'UUID' FROM player_data WHERE UUID ='%s'", id));
    
                while (resultSet.next()){
    
                    join(resultSet.getInt("numJoin"));
                    uuid((UUID) resultSet.getObject("UUID"));
                }
    
                statement.close();
                c.close();
    
            } catch (Exception e){
                e.printStackTrace();
            }
        }

    getJoin:

        public static int getJoin(UUID id){
            int i = 0;
            try {
    
                Connection c = getConnection();
                Statement statement = c.createStatement();
    
                i = statement.executeUpdate(String.format("SELECT 'numJoin', 'UUID' FROM player_data WHERE UUID ='%s'", id));
    
                statement.close();
    
                c.close();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return i;
        }

  12. imDaniX

    imDaniX
    Активный участник
    Пользователь

    Баллы:
    96
    Имя в Minecraft:
    imDaniX

    Повторюсь — я не вижу, что ты сохраняешь какие-либо данные.

  13. Вопрос, а как их тогда сохранять :D

    DataSave:

    public class DataSave implements Runnable{
    
        private boolean running = true;
    
        private static MySQLDataBase base;
    
        private static final List<Data> log = new ArrayList<>();
    
        private static Main plugin;
    
        public DataSave() {
            new Thread(this, "DataSaver").start();
        }
    
        @Override
        public void run() {
            while(running){
                saveList();
                try {
                    Thread.sleep(60000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        public void disable(){
            running = false;
        }
    
       public void saveData(Data dat){
            Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
                synchronized (Main.getInstance()){
                    log.add(dat);
                }
            });
        }
    
        public static void saveList() {
            synchronized (Main.getInstance()) {
                saveDat(log);
                log.clear();
                Main.getInstance().getLogger().warning("Success save data!");
            }
        }
    
        public static void loadBase(){
            try {
                Main.getInstance().getDataFolder().mkdir();
                base = new MySQLDataBase();
            } catch (Exception e) {
                Bukkit.getPluginManager().disablePlugin(plugin);
                e.printStackTrace();
            }
        }

  14. imDaniX

    imDaniX
    Активный участник
    Пользователь

    Баллы:
    96
    Имя в Minecraft:
    imDaniX

    Боюсь, тебе придется начать именно с изучения инструментов, а не тыкать пальцем в небо. В интернете достаточно гайдов по основам использования SQL в Java, в том числе и на русском.

  15. У меня вроде есть же метод, который сохраняет данные:

                                saveQuestion(getQuestion(sender_uuid), sender_uuid);
                                saveDat((List<Data>) new Data(sender_uuid, getJoin(sender_uuid), getQuestion(sender_uuid), getAnswer(sender_uuid), getBan(sender_uuid)));

    Или это не так работает?


  16. Code

    Code
    Старожил
    Пользователь

    Баллы:
    123
    Имя в Minecraft:
    _Gizmo

    я не оч понял на какой проблеме вы остановились
    но вот так делать не надо

           try {
               Connection c = getConnection();
               Statement statement = c.createStatement();
    
               ResultSet resultSet = statement.executeQuery(String.format("SELECT 'numJoin', 'UUID' FROM player_data WHERE UUID ='%s'", id));
    
               while (resultSet.next()){
    
                   join(resultSet.getInt("numJoin"));
                   uuid((UUID) resultSet.getObject("UUID"));
               }
    
               statement.close();
               c.close();
    
           } catch (Exception e){
               e.printStackTrace();
           }
    

    надо вот так

       try (Connection c = getConnection();
            PreparedStatement ps = c.prepareStatement("SELECT 'numJoin', 'UUID' FROM player_data WHERE UUID =?")) {
           ps.setString(1, id);
           try (ResultSet rs = ps.executeQuery()) {
               while(rs.next()) {
                   join(rs.getInt("numJoin"));
                   uuid((UUID) rs.getObject("UUID"));
               }
           }
       } catch (SQLException e) {
           e.printStackTrace();
       }
    
  17. Проблема сохранения. Он выводит количество, но вседа 0. Не реагирует на заход игрока в систему


  18. Code

    Code
    Старожил
    Пользователь

    Баллы:
    123
    Имя в Minecraft:
    _Gizmo

    а
    так ты сохраняешь селектами. так не работает)
    что вообще внутри join() и uuid() ?

Статус темы:

Закрыта.

Поделиться этой страницей

Русское сообщество Bukkit

Bukkit по-русски - свой сервер Minecraft

Понравилась статья? Поделить с друзьями:
  • Sql error trace oracle
  • Sql error too many connections sql error too many connections
  • Sql error state 23000
  • Sql error state 08006
  • Sql error ora 02291