Симптомы
Инструкция SQL отправляется из IBM DB2 в службу корпорации Майкрософт для распределенной реляционной базы данных архитектура (DRDA). Если инструкция содержит полное имя в кавычки идентификатора, такого как «SCHEMA1. В хост-системе IBM может отображаться Table1,» сообщение об ошибке, подобное приведенному ниже:
SQLCODE: -204
SQLSTATE: 42704
SQLERRMT: квалификатор.» НЕОПРЕДЕЛЕННОЕ ИМЯ
Причина
Эта проблема возникает, так как SQL преобразователь, который используется службой Microsoft для DRDA не правильно проанализировать и обновить полное идентификаторы в кавычках. Кроме того преобразователь SQL не обновляет имя сопоставленной коллекции в зависимости от параметров в файле App.config, который используется службой Microsoft для DRDA имя схемы.
Решение
Информация о накопительном пакете обновления
Исправление, устраняющее эту проблему включен в Накопительное обновление 1 для Microsoft узла Integration Server 2013.
Статус
Корпорация Майкрософт подтверждает, что это проблема продуктов Майкрософт, перечисленных в разделе «Относится к».
Нужна дополнительная помощь?
Нужны дополнительные параметры?
Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.
В сообществах можно задавать вопросы и отвечать на них, отправлять отзывы и консультироваться с экспертами разных профилей.
Submitted by: julian bui (jbu311)
Related to a bug found in the bug tracker. It looks like nobody did anything with that one because they didn’t have queries. I was able to duplicate the bug and here are the queries I used. Fields are censored for privacy reasons.
//NEXT THREE LINES EXECUTE WITHOUT ERRORS
String createTableQueryString = «CREATE TABLE MY_TABLE (aaaSMALLINT, bbbBIGINT, cccSMALLINT, ddd DOUBLE PRECISION, eee CHAR(16));»;
PreparedStatement ps = conn.prepareStatement(createTableQueryString);
ps.execute();
//NEXT FEWLINES PRODUCE ERROR:
try {
dataInsertPs = conn.prepareStatement(«INSERT INTO MY_TABLE (aaa, bbb, ccc, ddd, eee) VALUES (?, ?, ?, ?, ? )»);
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, «Could not create prepared statement», ex);
}
ERROR:
databaseURL = jdbc:firebirdsql:embedded:V:TempDB.FDB
Oct 22, 2008 1:24:06 PM Main createPreparedStatement
SEVERE: Could not create prepared statement
org.firebirdsql.jdbc.FBSQLException: GDS Exception. 335544569. Dynamic SQL Error
SQL error code = -204
Table unknown
MY_TABLE
At line 1, column 13
at org.firebirdsql.jdbc.AbstractPreparedStatement.<init>(AbstractPreparedStatement.java:127)
at org.firebirdsql.jdbc.FBPreparedStatement.<init>(FBPreparedStatement.java:41)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.firebirdsql.jdbc.FBStatementFactory.createPreparedStatement(FBStatementFactory.java:90)
at org.firebirdsql.jdbc.AbstractConnection.prepareStatement(AbstractConnection.java:869)
at org.firebirdsql.jdbc.AbstractConnection.prepareStatement(AbstractConnection.java:824)
at org.firebirdsql.jdbc.AbstractConnection.prepareStatement(AbstractConnection.java:817)
at org.firebirdsql.jdbc.AbstractConnection.prepareStatement(AbstractConnection.java:293)
at Main.createPreparedStatement(Main.java:101)
at Main.main(Main.java:189)
I created local database in DB2 called «TestDB» then I created table called «TestTable«.
I found that the table is put under schema name is «yasmin«.
I am trying to connect to the DB2 database using JDBC but I got this exception
R SQLException information
[1/4/14 11:32:59:289 EST] 0000004d SystemErr R Error msg: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.TESTTABLE, DRIVER=3.61.86
[1/4/14 11:32:59:290 EST] 0000004d SystemErr R SQLSTATE: 42704
[1/4/14 11:32:59:290 EST] 0000004d SystemErr R Error code: -204
[1/4/14 11:32:59:290 EST] 0000004d SystemErr R com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.TESTTABLE, DRIVER=3.61.86
I tried many solutions on the internet Like set schema but unfortunately doesn’t work.
This is the JDBC code I used
String urlPrefix = "jdbc:db2:";
String url;
String user;
String password;
String empNo;
Connection con;
Statement stmt;
ResultSet rs;
url = urlPrefix + "//127.0.0.1:50000/TestDB";
user = "db2admin";
password = "db2admin";
try
{
// Load the driver
Class.forName("com.ibm.db2.jcc.DB2Driver");
System.out.println("**** Loaded the JDBC driver");
// Create the connection using the IBM Data Server Driver for JDBC and SQLJ
con = DriverManager.getConnection (url, user, password);
// Commit changes manually
con.setAutoCommit(false);
System.out.println("**** Created a JDBC connection to the data source");
stmt = con.createStatement(); con.createStatement();
System.out.println("**** Created JDBC Statement object");
// Execute a query and generate a ResultSet instance
rs = stmt.executeQuery("select *from TestTable");
System.out.println("**** Created JDBC ResultSet object");
}
catch (ClassNotFoundException e)
{
System.err.println("Could not load JDBC driver");
System.out.println("Exception: " + e);
e.printStackTrace();
}
catch(SQLException ex)
{
System.err.println("SQLException information");
while(ex!=null) {
System.err.println ("Error msg: " + ex.getMessage());
System.err.println ("SQLSTATE: " + ex.getSQLState());
System.err.println ("Error code: " + ex.getErrorCode());
ex.printStackTrace();
ex = ex.getNextException(); // For drivers that support chained exceptions
}
}
Chris Snow
23.6k33 gold badges141 silver badges307 bronze badges
asked Jan 4, 2014 at 9:38
0
As @Mark Rotteveel said, the -204 error is from a missing object, but it’s missing for a reason other than what he said.
It’s not found because you did not prefix it with the schema name. You said above that it’s in schema yasmin, but you’re connecting with db2admin, so it’s trying to look for db2admin.TestTable.
SELECT * FROM yasmin.TestTable
should be what you’re looking for.
By default, the search path for schemas is the name of the currently connecting user. You can see what it is using
SELECT CURRENT SCHEMA FROM SYSIBM.SYSDUMMY1
If you want to change it, you can use the SET SCHEMA command to change the search path, but usually it’s easier just to include the schema name in your query.
answered Jan 4, 2014 at 19:51
bhambybhamby
15.1k1 gold badge45 silver badges66 bronze badges
1
The error SQLERROR -204, SQLSTATE 42704 is a missing/unknown objectname and it is most likely caused by a missing space in:
rs = stmt.executeQuery("select *from TestTable");
Which should be:
rs = stmt.executeQuery("select * from TestTable");
answered Jan 4, 2014 at 11:05
Mark RotteveelMark Rotteveel
99.2k188 gold badges137 silver badges192 bronze badges
2
The problem was The table I created in db2 has schema name "yasmin"
I used username and password "db2admin/db2admin" In JDBC connection
so it search for the table in this schema «db2admin»
so I need to set the schema to be "yasmin"
so I added the following lines of code after creating
the connection
String schemaName="yasmin";
if (schemaName != null && schemaName.length() != 0) {
try {
statement = connection.createStatement();
statement.executeUpdate("set current sqlid = " + schemaName);
System.out.println("The schema is set successfully.");
} catch (SQLException exception) {
exception.printStackTrace();
}
and grant db2admin all privilages on this table in db2
1-Right click on the table choose privilages
2-Click on «Add user» button
3-then write the username «db2admin» and click «apply» button
4-Then select the user you just add and click «gtant all» button
Now he can see the table.
Many Thanks @Mark Rotteveel and @bhamby for your help.
answered Jan 5, 2014 at 20:29
YasminYasmin
1831 gold badge2 silver badges11 bronze badges
If you are connecting in Spring using Hibernate use following in the property line
<property name="url" value="jdbc:db2://<ip>:<port>/<database>:currentSchema=<currentSchema>;" />
answered Mar 24, 2015 at 11:50
1
Other way is just create an ALIAS, likes this:
CREATE ALIAS USER1.YOURTABLE FOR TABLE USER2.YOURTABLE;
JoSSte
2,8866 gold badges33 silver badges52 bronze badges
answered Nov 26, 2015 at 6:31
From Wikipedia, the free encyclopedia
SQL Return Codes are used on a day-to-day basis for the diagnosis of programming failures as a result of SQL calls by IBM Db2 programs. An important feature of IBM Db2 programs is the error processing. The error diagnostic containing the SQL Return Code is held in the field SQLCODE within the Db2 SQLCA block.
SQLCODE is no longer part of the SQL-standard. The SQL-standard replaced SQLCODE by the more detailed SQLSTATE.
SQLCA[edit]
The SQL communications area (SQLCA) structure is used within the IBM Db2 program to return feedback to the application program.
SQLCODE[edit]
The SQLCODE field contains the SQL return code. The code can be zero (0), negative or positive:
- 0 means that the execution was successful.
- Negative values indicate an unsuccessful execution with an error.
An example is -911, which means that a timeout has occurred with a rollback. - Positive value mean a successful execution with a warning.
An example is +100, which means that no matching rows were found or that the cursor has reached the end of the table.
Here is a more comprehensive list of the SQLCODEs for DB2. Note that this list is not exhaustive. Also note that some SQLCODEs may only occur in specific Db2 products; e.g., only on Db2 z/OS, only on Db2 LUW, or only on Db2 for IBM i.
Zero (Successful)[edit]
0 Successful
Negative values (Errors)[edit]
| -007 | The specified ‘character’ is not a valid character in SQL statements. |
| -010 | THE string constant beginning with string is not terminated properly. |
| -029 | INTO Clause required. |
| -060 | INVALID type SPECIFICATION : spec |
| -084 | Unacceptable SQL statement. |
| -101 | The statement is too long or too complex. |
| -102 | String constant is too long. |
| -103 | String constant is too long. Max is 128 characters. |
| -104 | Illegal symbol encountered in the SQL statement. |
| -105 | String constant is too long. |
| -117 | The number of values in the INSERT does not match the number of columns. |
| -119 | Error in GROUP BY or HAVING clause. |
| -122 | Column or Expression in the Select List is not valid |
| -156 | Invalid syntax near keyword. |
| -180 | Bad data in Date/Time/Timestamp. |
| -181 | Bad data in Date/Time/Timestamp. |
| -188 | The host variable in a DESCRIBE statement is not a valid string representation of a name. |
| -199 | Illegal use of the specified keyword. |
| -203 | A REFERENCE TO COLUMN column-name IS AMBIGUOUS |
| -204 | Object not defined to Db2. |
| -205 | Column name not in table. |
| -206 | Column does not exist in any table of the SELECT. |
| -207 | Invalid column name. |
| -208 | THE ORDER BY CLAUSE IS INVALID BECAUSE COLUMN column-name IS NOT PART OF THE RESULT TABLE |
| -209 | Ambiguous column name |
| -216 | Not the same number of expressions on both sides of the comparison in a SELECT. |
| -224 | FETCH cannot make an INSENSITIVE cursor SENSITIVE. |
| -229 | The locale specified in a SET LOCALE statement was not found. |
| -257 | Implicit conversion in datatype is not allowed. |
| -289 | Db2 is running out of space in tablespace |
| -302 | THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE |
| -303 | A VALUE CANNOT BE ASSIGNED TO OUTPUT HOST VARIABLE NUMBER position-number BECAUSE THE DATA TYPES ARE NOT COMPARABLE |
| -305 | Null indicator needed. |
| -310 | The value of a decimal is null |
| -311 | Varchar, insert or update. -LEN field with the right data length not set. |
| -313 | The number of host variables specified is not equal to the number of parameter markers. |
| -401 | The data types of the operands of an operation are not compatible. |
| -404 | The Sql Statement specified contains a String that is too long. |
| -407 | AN UPDATE, INSERT, OR SET VALUE IS NULL, BUT THE OBJECT COLUMN column-name CANNOT CONTAIN NULL VALUES |
| -408 | A value is not compatible with the data type of its assignment target. Target name is «<name>». (***OBS: Para alguns casos o CAST resolve ) |
| -413 | Overflow occurred during numeric data type conversion. |
| -414 | A like predicate is invalid because the first operand is not a string. |
| -415 | The corresponding columns, column-number, of the operands of a set operator are not compatible. |
| -418 | Use of parameter marker not valid. |
| -420 | The value of a string argument was not acceptable to the ‘function-name’ function |
| -421 | THE OPERANDS OF A UNION OR UNION ALL DO NOT HAVE THE SAME NUMBER OF COLUMNS |
| -433 | The data is too large |
| -438 | Application raised error with diagnostic text: text |
| -440 | Routine &1 in &2 not found with specified parameters.A function or procedure with the specified name and compatible arguments was not found.[1] |
| -482 | The procedure returned no locators. |
| -501 | Cursor not open on FETCH. |
| -502 | Opening cursor that is already open. |
| -503 | Updating column needs to be specified. |
| -504 | Cursor name not declared. |
| -510 | The Table designated by the cursor of the Update or Delete statement cannot be modified. |
| -530 | Referential integrity preventing the INSERT/UPDATE |
| -532 | Referential integrity (DELETE RESTRICT rule) preventing the DELETE. |
| -536 | Referential integrity (DELETE RESTRICT rule) preventing the DELETE. |
| -545 | Check constraint preventing the INSERT/UPDATE. |
| -551 | Authorization failure. |
| -554 | An authorization ID or a role cannot GRANT a privilege to itself. |
| -601 | You tried to create an object that already exists |
| -602 | Too many columns specified in a create index. |
| -603 | a unique index cannot be created because the table contains rows which are duplicates with respect to the values of the identified columns and periods |
| -604 | a data type definition specifies an invalid length, precision, or scale attribute |
| -607 | operation or option operation is not defined for this object |
| -610 | warning: a create/alter on object has placed object in pending |
| -611 | only lockmax 0 can be specified when the lock size of the tablespace is tablespace or table |
| -612 | identifier is a duplicate name |
| -613 | the primary key or a hash key or a unique constraint is too long or has too many columns and periods |
| -614 | the index cannot be created or altered, or the length of a column cannot be changed because the sum of the internal lengths of the columns for the index is greater than the allowable maximum |
| -615 | operation-type is not allowed on a package in use |
| -616 | obj-type1 obj-name1 cannot be dropped because it is referenced by obj-type2 obj-name2 |
| -617 | a type 1 index is not valid for table |
| -618 | operation operation is not allowed on system databases |
| -619 | operation disallowed because the database is not stopped |
| -620 | keyword keyword in stmt-type statement is not permitted for a space-type space in the database-type database |
| -621 | duplicate dbid dbid was detected and previously assigned to database-name |
| -622 | for mixed data is invalid because the mixed data install option is no |
| -623 | cluster is not valid for table-name |
| -624 | table table-name already has a primary key or unique constraint with specified columns and periods |
| -625 | table table-name does not have an index to enforce the uniqueness of the primary or unique key |
| -625 | warning: the definition of table has been changed to incomplete |
| -626 | the alter statement is not executable because the page set is not stopped |
| -627 | the alter statement is invalid because the table space or index has user-managed data sets |
| -628 | the clauses are mutually exclusive |
| -629 | set null cannot be specified because foreign key name cannot contain null values |
| -630 | error: the WHERE NOT NULL specification is invalid for type 1 indexes |
| -631 | foreign key name is too long or has too many columns |
| -632 | the table cannot be defined as a dependent of table-name because of DELETE rule restrictions |
| -633 | the DELETE rule must be DELETE-rule |
| -634 | the DELETE rule must not be cascade |
| -635 | the DELETE rules cannot be different or cannot be set null |
| -636 | ranges specified for partition part-num are not valid |
| -637 | duplicate keyword-name keyword or clause |
| -638 | table table-name cannot be created because column definition is missing |
| -639 | a nullable column of a foreign key with a DELETE rule of set null cannot be a column of the key of a partitioned index |
| -640 | locksize row cannot be specified because table in this tablespace has type 1 index |
| -642 | too many columns in unique constraints |
| -643 | a check constraint or the value of an expression for a column of an index exceeds the maximum allowable length key expression |
| -644 | invalid value specified for keyword or clause keyword-or-clause in statement stmt-type |
| -645 | WHERE NOT NULL is ignored because the index key cannot contain null values |
| -646 | table table-name cannot be created in specified table space table-space-name because it already contains a table |
| -647 | bufferpool bp-name for implicit or explicit tablespace or indexspace name has not been activated |
| -650 | the alter statement cannot be executed, reason reason-code copyright 2014 TheAmericanProgrammer.com Unauthorized copying prohibited |
| -651 | table description exceeds maximum size of object descriptor. |
| -652 | violation of installation defined edit or validation procedure proc-name |
| -653 | table table-name in partitioned table space tspace-name is not available because its partitioned index has not been created |
| -655 | the create or alter stogroup is invalid because the storage group would have both specific and non-specific volume ids |
| -658 | a object-type cannot be dropped using the statement statement |
| -660 | index index-name cannot be created or altered on partitioned table space tspace-name because key limits are not specified |
| -661 | object-type object-name cannot be created on partitioned table space tspace-name because the number of partition specifications is not equal to the number of partitions of the table space |
| -662 | a partitioned index cannot be created on a table space, or a table space cannot be index-controlled. table space tspace-name, reason reason-code |
| -663 | the number of key limit values is either zero, or greater than the number of columns in the key of index index-name |
| -664 | the internal length of the limit-key fields for the partitioned index exceeds the length imposed by the index manager |
| -665 | the partition clause of an alter statement is omitted or invalid |
| -666 | stmt-verb object cannot be executed because function is in progress |
| -667 | the clustering index for a partitioned table space cannot be explicitly dropped |
| -668 | the column cannot be added to the table because the table has an edit procedure defined with row attribute sensitivity |
| -669 | the object cannot be explicitly dropped. reason reason-code |
| -670 | the record length of the table exceeds the page size limit |
| -671 | the bufferpool attribute of the table space cannot be altered as specified because it would change the page size of the table space |
| -672 | operation drop not allowed on table table_name |
| -676 | the physical characteristics of the index are incompatible with respect to the specified statement. the statement has failed. reason reason-code |
| -677 | insufficient virtual storage for bufferpool expansion |
| -678 | the constant specified for the index limit key must conform to the data type data-type of the corresponding column column-name |
| -679 | the object name cannot be created because a drop is pending on the object |
| -680 | too many columns specified for a table, view or table function |
| -681 | column column-name in violation of installation defined field procedure. rt: return-code, rs: reason-code, msg: message-token |
| -682 | field procedure procedure-name could not be loaded |
| -683 | the specification for column, distinct type, function, or procedure data-item contains incompatible clauses |
| -684 | the length of constant list beginning string is too long |
| -685 | invalid field type, column-name |
| -686 | column defined with a field procedure can not compare with another column with different field procedure |
| -687 | field types incomparable |
| -688 | incorrect data returned from field procedure, column-name, msgno |
| -689 | too many columns defined for a dependent table |
| -690 | the statement is rejected by data definition control support. reason reason-code |
| -691 | the required registration table table-name does not exist |
| -692 | the required unique index index-name for ddl registration table table-name does not exist |
| -693 | the column column-name in ddl registration table or index name is not defined properly |
| -694 | the schema statement cannot be executed because a drop is pending on the ddl registration table table-name |
| -694 | the ddl statement cannot be executed because a drop is pending on the ddl registration table |
| -695 | invalid value seclabel specified for security label column of table table-name |
| -696 | the definition of trigger trigger-name includes an invalid use of correlation name or transition table name name. reason code=reason-code |
| -697 | old or new correlation names are not allowed in a trigger defined with the for each statement clause. old_table or new_table names are not allowed in a trigger with the before clause. |
| -747 | The table is not available. |
| -803 | Duplicate key on insert or update. |
| -804 | Error in input parameters for the SQL statement. |
| -805 | DBRM or package not found in plan. |
| -811 | More than one row retrieved in SELECT INTO. |
| -818 | Plan and program: timestamp mismatch. |
| -902 | Pointer to Essential Control Block(RDA/CT) has value 0, Rebind Required. This may also occur if one of the DB volumes is still present, but inaccessible. |
| -904 | Unavailable resource. Someone else is locking your data. |
| -911 | Deadlock or timeout. Rollback has been done. |
| -913 | Deadlock or timeout. No rollback. |
| -922 | Authorization needed. |
| -924 | Db2 Connection internal error. |
| -927 | The language interface was called but no connection had been made. |
| -955 | Sort memory cannot be allocated to process the statement. |
| -964 | The transaction log space is depleted or temporary increase in the number of active transactions. |
| -970 | wrong (also missing) permissions on Db2 file systems / Db2 filesystems owned by root. |
| -998 | Error occurred during transaction or heuristic processing. |
| -2310 | The utility could not generate statistics |
| -3508 | Load Error accessing scratch space. Error in accessing a file or path of type «TEMP_FILE» during load or load query. The scratch directory where the msg files in a load job are stored does not have the required permissions. |
| -7008 | The object that is specified is not valid for the requested operation. |
| -10330 | Permission denied to change database. Contact system administrator. |
| -30090 | Remote operation invalid for application execution environment. |
[1]
Positive Values (Warnings)[edit]
| +98 | A dynamic SQL statement ends with a semicolon |
| +100 | Row not found or end of cursor. |
| +222 | Trying to fetch a row within a DELETE statement. |
| +223 | Trying to fetch a row within an UPDATE statement. |
| +231 | FETCH after a BEFORE or AFTER but not on a valid row. |
| +304 | A value with data type (data type 1) cannot be assigned to a host variable because the value is not within the range of the host variable in position (position number) with data type (data type 2) |
| +354 | A rowset fetch statement may have returned one or more rows of data. however, one or more warning conditions were also encountered. use the get diagnostics statement for more information regarding the conditions that were encountered |
| +562 | A grant of a privilege was ignored because the grantee already has the privilege from the grantor. |
| +802 | The null indicator was set to -2 as an arithmetic. |
References[edit]
- ^ «IBM Docs».
- «DB2 Version 9.1 for z/OS Codes» (PDF). September 2013.
- «DB2 SQL CODE Description and solutions».
- «SQL codes». September 2013.
Советы и рекомендации по DB2. Часть 57 — Как выявить конкретный код ошибки с помощью утилиты db2pdcfg
Я создал локальную базу данных в DB2 под названием «TestDB«затем я создал таблицу»TestTable‘. Я обнаружил, что таблица помещена под именем схемы «yasmin‘. Я пытаюсь подключиться к DB2 база данных с использованием JDBC но у меня есть это исключение
R SQLException information [1/4/14 11:32:59:289 EST] 0000004d SystemErr R Error msg: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.TESTTABLE, DRIVER=3.61.86 [1/4/14 11:32:59:290 EST] 0000004d SystemErr R SQLSTATE: 42704 [1/4/14 11:32:59:290 EST] 0000004d SystemErr R Error code: -204 [1/4/14 11:32:59:290 EST] 0000004d SystemErr R com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.TESTTABLE, DRIVER=3.61.86
Я пробовал много решений в Интернете. Как и установленная схема, но, к сожалению, не работает.
Это код JDBC, который я использовал
String urlPrefix = 'jdbc:db2:'; String url; String user; String password; String empNo; Connection con; Statement stmt; ResultSet rs; url = urlPrefix + '//127.0.0.1:50000/TestDB'; user = 'db2admin'; password = 'db2admin'; try { // Load the driver Class.forName('com.ibm.db2.jcc.DB2Driver'); System.out.println('**** Loaded the JDBC driver'); // Create the connection using the IBM Data Server Driver for JDBC and SQLJ con = DriverManager.getConnection (url, user, password); // Commit changes manually con.setAutoCommit(false); System.out.println('**** Created a JDBC connection to the data source'); stmt = con.createStatement(); con.createStatement(); System.out.println('**** Created JDBC Statement object'); // Execute a query and generate a ResultSet instance rs = stmt.executeQuery('select *from TestTable'); System.out.println('**** Created JDBC ResultSet object'); } catch (ClassNotFoundException e) { System.err.println('Could not load JDBC driver'); System.out.println('Exception: ' + e); e.printStackTrace(); } catch(SQLException ex) { System.err.println('SQLException information'); while(ex!=null) { System.err.println ('Error msg: ' + ex.getMessage()); System.err.println ('SQLSTATE: ' + ex.getSQLState()); System.err.println ('Error code: ' + ex.getErrorCode()); ex.printStackTrace(); ex = ex.getNextException(); // For drivers that support chained exceptions } }
- Плз, мне нужна твоя помощь. Вопрос просматривается 10 раз, ответа нет. Если вопрос не ясен, скажите мне, какую дополнительную информацию я должен добавить.
Как сказал @Mark Rotteveel, -204 ошибка связана с отсутствующим объектом, но он отсутствует по причине, отличной от указанной.
Он не найден, потому что вы не добавили к нему префикс имени схемы. Вы сказали выше, что это в схеме yasmin, но вы подключаетесь к db2admin, поэтому он пытается искать db2admin.TestTable.
SELECT * FROM yasmin.TestTable
должно быть то, что вы ищете.
По умолчанию путь поиска схем — это имя текущего подключающегося пользователя. Вы можете увидеть, что он использует
SELECT CURRENT SCHEMA FROM SYSIBM.SYSDUMMY1
Если вы хотите изменить его, вы можете использовать команду SET SCHEMA для изменения пути поиска, но обычно проще просто включить имя схемы в ваш запрос.
- К сожалению, я использовал этот запрос раньше, но он тоже не работает. Я попытался установить схему таблицы в db2 как «db2admin» с помощью запроса и проверить текущую схему с помощью запроса. это изменило. После этого, если я просматриваю схему таблицы, тот же «ясмин» не меняется.
Ошибка SQLERROR -204, SQLSTATE 42704 — это отсутствующее / неизвестное имя объекта, и, скорее всего, это вызвано отсутствием места в:
rs = stmt.executeQuery('select *from TestTable');
Что должно быть:
rs = stmt.executeQuery('select * from TestTable');
- Извините, но я не знаю, о каком пространстве вы говорите?
- @Yasmin Тогда, скорее всего, у вас нет таблицы с именем
TestTable, или его необходимо указать с учетом регистра.
Проблема заключалась в том, что таблица, которую я создал в db2, имеет имя схемы 'yasmin'
Я использовал логин и пароль 'db2admin/db2admin' В соединении JDBC
поэтому он ищет таблицу в этой схеме «db2admin»
поэтому мне нужно установить схему как 'yasmin'
поэтому я добавил следующие строки кода после создания подключения
String schemaName='yasmin'; if (schemaName != null && schemaName.length() != 0) { try { statement = connection.createStatement(); statement.executeUpdate('set current sqlid = ' + schemaName); System.out.println('The schema is set successfully.'); } catch (SQLException exception) { exception.printStackTrace(); }
и предоставьте db2admin все привилегии для этой таблицы в db2
1-Щелкните правой кнопкой мыши по таблице и выберите привилегии
2-Нажмите кнопку «Добавить пользователя».
3-затем введите имя пользователя «db2admin» и нажмите кнопку «Применить»
4-Затем выберите пользователя, которого вы только что добавили, и нажмите кнопку «gtant all».
Теперь он может видеть стол.
Большое спасибо @Mark Rotteveel и @bhamby за вашу помощь.
Если вы подключаетесь в Spring с помощью Hibernate, используйте следующую строку в строке свойств
Другой способ — просто создать АЛИАС, например:
CREATE ALIAS USER1.YOURTABLE FOR TABLE USER2.YOURTABLE;
Tweet
Share
Link
Plus
Send
Send
Pin
The error code -204 says:
The object name is undefined. Resolution is need to check if the DB2 object name is correct.
| Errors | Resolutions |
|---|---|
| -204 | Check object name |
| -205 | Check column name |
| -206 | Check object names |
The error code -205 says:
Invalid column name. In other way, the column name is not defined on that table. Resolution is check if that column name is created during Table creation.
The error code -206 says:
Similar to error -204, the column name is invalid in the context of SELECT, INSERT, DELETE or MERGE
Related Posts
