Psql error relation couriers does not exist

Debugging “relation does not exist” error in postgres So, i was getting this nasty error even when the table clearly existed in t11 database. Even after lot of googling, debugging and trying Stackoverflow solutions, there was no resolution. Then i got a hunch, that i should check what database and schema were actually being […]

Содержание

  1. Debugging “relation does not exist” error in postgres
  2. Нельзя просто использовать имя таблицы PostgreSQL («отношение не существует»)
  3. 7 ответов:
  4. Нельзя просто использовать имя таблицы PostgreSQL («отношения не существует»)
  5. org.postgresql.util.PSQLException: ОШИБКА: отношение «app_user» не существует
  6. 3 ответа
  7. Java SQL «ОШИБКА: отношение» Имя_таблицы «не существует»
  8. 4 ответы

Debugging “relation does not exist” error in postgres

So, i was getting this nasty error even when the table clearly existed in t11 database.

Even after lot of googling, debugging and trying Stackoverflow solutions, there was no resolution. Then i got a hunch, that i should check what database and schema were actually being used when done programmatically (even though dbname was clearly provided in connection string).

If you use database t11 by running c t11 and then run:

select * from information_schema.tables where table_schema NOT IN (‘pg_catalog’, ‘information_schema’)

It will tell you that userinfo5 does exist in t11 database. But what happens when we try to access it programmatically?

So, i ran above query in a golang function, the function which was earlier running query select * from userinfo5 where >

Output showed that database name which was actually being used was postgres and not t11 Why?

Because, my postgres user was configured to not use password. But my connection string had password= This was somehow confusing the DB driver and postgres database was being used and not t11 .

remove password= from connection string so that it looks like: “host=localhost port=5432 user=postgres dbname=t11 sslmode=disable”

  1. Alter user postgres so that it uses password: alter user postgres with password ‘pwd123’;
  2. Change connection string: “host=localhost port=5432 user=postgres password=pwd123 dbname=t11 sslmode=disable”

Источник

Нельзя просто использовать имя таблицы PostgreSQL («отношение не существует»)

Я пытаюсь запустить следующий PHP-скрипт для выполнения простого запроса к базе данных:

это приводит к следующей ошибке:

ошибка запроса: ошибка: отношение «sf_bands» не существует

во всех примерах я могу найти, где кто-то получает ошибку о том, что связь не существует, это потому, что они используют прописные буквы в имени своей таблицы. Мое имя таблицы не имеет прописных букв. Есть ли способ запросить мою таблицу без включения имени базы данных, т. е. showfinder.sf_bands ?

7 ответов:

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

другими словами, следующее терпит неудачу:

используйте двойные кавычки для разграничения идентификаторов, чтобы вы могли использовать конкретное смешанное написание, как определено в таблице.

Re ваш комментарий, вы можете добавить схему в «search_path», чтобы при ссылке на имя таблицы без уточнения ее схемы запрос соответствовал этому имени таблицы, проверяя каждую схему по порядку. Так же, как PATH в оболочке или include_path в PHP и др. Вы можете проверить свой текущий путь поиска схема:

вы можете изменить путь поиска схемы:

у меня были проблемы с этим и это история (печальная, но правдивая) :

если ваше имя таблицы все строчные, как: счета вы можете использовать: select * from AcCounTs и он будет работать нормально

если ваше имя таблицы все строчные, как: accounts Следующее не удастся: select * from «AcCounTs»

если ваше имя таблицы смешанный случай как: Accounts Следующее не удастся: select * from accounts

если ваше имя таблицы это смешанный случай как : Accounts Следующее будет работать нормально: select * from «Accounts»

Я не люблю вспоминать бесполезные вещи, как это, но надо 😉

запрос процесса Postgres отличается от других RDMS. Поместите имя схемы в двойную кавычку перед именем таблицы, например, «SCHEMA_NAME».»SF_Bands»

поместите параметр dbname в строку подключения. Это работает для меня, в то время как все остальное не удалось.

также, когда делаешь выбор, указать your_schema . your_table такой:

У меня была аналогичная проблема на OSX, но я пытался играть с двойными и одинарными кавычками. Для вашего случая, вы могли бы попробовать что-то вроде этого

для меня проблема заключалась в том, что я использовал запрос к этой конкретной таблице во время инициализации Django. Конечно, это вызовет ошибку, потому что эти таблицы не существовали. В моем случае это было get_or_create метод в пределах a admin.py файл, который выполнялся всякий раз, когда программное обеспечение выполняло какую-либо операцию (в данном случае миграцию). Надеюсь, это кому-то поможет.

я копал эту проблему больше, и узнал о том, как установить этот «search_path» по defoult для нового пользователя в текущей базе данных.

открыть Свойства базы данных, затем открыть лист » переменные» и просто добавьте эту переменную для вашего пользователя с фактическим значением.

Так что теперь ваш пользователь получит это schema_name по умолчанию, и вы можете использовать tableName без schemaName.

Источник

Нельзя просто использовать имя таблицы PostgreSQL («отношения не существует»)

Я пытаюсь запустить следующий скрипт PHP, чтобы выполнить простой запрос к базе данных:

Это приводит к следующей ошибке:

Ошибка запроса: ERROR: отношения «sf_bands» не существует

Во всех примерах я могу найти, где кто-то получает ошибку, указывающую, что отношения не существует, потому что они используют заглавные буквы в имени своей таблицы. В моем имени таблицы нет заглавных букв. Есть ли способ запросить мою таблицу без включения имени базы данных, то есть showfinder.sf_bands ?

Из того, что я прочитал, эта ошибка означает, что вы неправильно ссылаетесь на имя таблицы. Одной из распространенных причин является то, что таблица определена с орфографией с смешанным регистром, и вы пытаетесь запросить ее со всеми строчными буквами.

Другими словами, следующее не выполняется:

Используйте двойные кавычки, чтобы разграничить идентификаторы, чтобы вы могли использовать конкретную орфографию с смешанным регистром, поскольку таблица определена.

Повторите свой комментарий, вы можете добавить схему в «путь поиска», чтобы при ссылке на имя таблицы без квалификации ее схемы запрос соответствовал этому имени таблицы, проверив каждую схему в порядке. Точно так же, как PATH в оболочке или include_path в PHP и т. Д. Вы можете проверить свой текущий путь поиска схемы:

Вы можете изменить путь поиска схемы:

У меня были проблемы с этим, и это история (грустная, но правда):

Если имя вашей таблицы имеет нижний регистр, например: учетные записи, которые вы можете использовать: select * from AcCounTs и он будет работать нормально

Если ваше имя таблицы имеет все нижеследующее значение, например: accounts Следующие select * from «AcCounTs» не будут выполнены: select * from «AcCounTs»

Если ваше имя таблицы смешанно, например: Accounts : Accounts : select * from accounts

Если ваше имя таблицы смешанно, например: Accounts Следующие будут работать нормально: select * from «Accounts»

Я не люблю вспоминать бесполезные вещи, как это, но вы должны;)

Запрос процесса Postgres отличается от других RDMS. Поместите имя схемы в двойную кавычку перед именем вашей таблицы, например «SCHEMA_NAME». «SF_Bands»

Поместите параметр dbname в строку подключения. Это работает для меня, пока все остальное не удалось.

Также, когда вы делаете выбор, укажите your_schema . your_table :

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

Источник

org.postgresql.util.PSQLException: ОШИБКА: отношение «app_user» не существует

У меня есть приложение, в котором я использую spring boot и postgres. Я получаю эту ошибку, когда пытаюсь создать пользователя.

Когда я запускаю этот запрос в своей базе данных, я получаю ту же ошибку:

Но если я изменил это на:

Как мне настроить это приложение для загрузки spring?

зависимости в pom.xml:

Я вызываю это действие из формы:

и это мой контроллер:

Валидатор, который исправляет ошибку:

И репозиторий является интерфейсом CrudRepository и не имеет реализации:

И отлаживая валидатор, я мог бы получить этот стек:

Спасибо за помощь!

3 ответа

PostgreSQL соответствует стандарту SQL и в этом случае означает, что идентификаторы (имена таблиц, имена столбцов и т.д.) принудительно строятся в нижнем регистре, за исключением случаев, когда они цитируются. Поэтому, когда вы создаете таблицу следующим образом:

вы фактически получаете таблицу app_user . Вы, очевидно, сделали:

а затем вы получите таблицу «APP_USER» .

В Spring вы указываете правильную строку для имени таблицы заглавными буквами, но ее объединяют в запрос на сервер PostgreSQL без кавычек. Вы можете проверить это, прочитав файлы журнала PostgreSQL: он должен показать запрос, сгенерированный Spring, за которым следует ошибка в верхней части вашего сообщения.

Поскольку у вас очень мало контроля над тем, как Spring строит запросы от сущностей, вам лучше использовать идентификаторы нижнего регистра стандарта SQL.

Источник

Java SQL «ОШИБКА: отношение» Имя_таблицы «не существует»

Я пытаюсь подключить netbeans к моей базе данных postgresql. Кажется, что соединение сработало, поскольку я не получаю никаких ошибок или исключений при простом подключении, такие методы, как getCatalog (), также возвращают правильные ответы.

Но когда я пытаюсь запустить простой оператор SQL, я получаю сообщение об ошибке «ОШИБКА: отношение« TABLE_NAME »не существует», где TABLE_NAME — это любая из моих таблиц, которые ДЕЙСТВИТЕЛЬНО существуют в базе данных. Вот мой код:

Я думал, что netbeans может не находить таблицы, потому что он не ищет схему по умолчанию (общедоступную), есть ли способ установить схему в java?

РЕДАКТИРОВАТЬ: мой код подключения. Имя базы данных — Cinemax, когда я опускаю код оператора, я не получаю ошибок.

Разве нельзя так переписать sql? SELECT * FROM .clients — CoolBeans

Вы не показываете, как вы подключаетесь к серверу базы данных. Я подозреваю, что @CoolBeans верен выше или очень близко. Ваша таблица находится в другой схеме (что будет исправлено выше) или в другой базе данных, чем та, которую вы указали при подключении. — Brian Roach

Мне это нравится . не могли бы вы показать нам НАСТОЯЩУЮ ошибку? Я не думаю, что база данных говорит «отношение TABLE_NAME . », когда вы выполняете «select * from clients». — Szymon Lipiński

Я пробовал это, но получаю ту же ошибку: «ОШИБКА: отношение« public.clients »не существует» (то же самое для любой другой из моих таблиц). public — моя единственная схема, так что это также схема по умолчанию. Спасибо за помощь. — Matt

Установите для log_min_duration_statement значение 0 в postgresql.conf, перезапустите базу данных, запустите приложение и проверьте в журналах postgresql, какой реальный запрос отправляется в базу данных. И еще кое-что . вы на 100% уверены, что у вас есть стол? Можете ли вы подключиться к этой базе данных с помощью psql / pgadmin и выполнить там запрос? — Szymon Lipiński

4 ответы

Я подозреваю, что вы создали таблицу, используя двойные кавычки, например, «Clients» или какая-либо другая комбинация символов верхнего / нижнего регистра, поэтому имя таблицы теперь чувствительно к регистру.

Что означает заявление

Если возвращаемое имя таблицы не в нижнем регистре, вы должны использовать двойные кавычки при обращении к нему, что-то вроде этого:

ответ дан 24 апр.

Я пытаюсь использовать sequelize ORM, и в своем запросе на создание он использует кавычки в table_name. Спасибо за ответ. — Kiddo

Источник

What are you doing?

edit2: Remember folks, when you change your env variables, you have to restart your server/pm2 instance =) This fixed it, although I would expect a more helpful error message when host, port etc. are undefined.

Hey guys,

I am switching my node/express app from mysql to postgresql. Everything was pretty seamless except I had to swap some data types. When I try to run the following command I get an error.

edit: Looks like something else is up. Sequelize throws the same error for all other queries, including relation "users" does not exist. I know this was marked as support, but mysql was working perfectly before changing to postgres, so I imagine it should also work now.

const [ serviceUser, created ] = await ServiceUserAccountModel.findOrCreate({ 
          where: { service_user_id: '123456' },
        });

relation "serviceUserAccounts" does not exist. or with users relation "users" does not exist

const userModel = Sequelize.define('user', {
    // has many ServiceUserAccounts

    id: { 
      type: DataTypes.INTEGER, 
      primaryKey: true, 
      autoIncrement: true 
    },

    email: {
      type: DataTypes.STRING,
      allowNull: false
    },

    age: {
      type: DataTypes.SMALLINT,
      allowNull: false
    },

    gender: {
      type: DataTypes.STRING,
      allowNull: false
    },

    first_name: {
      type: DataTypes.STRING,
      allowNull: true
    },

    last_name: {
      type: DataTypes.STRING,
      allowNull: true
    }
       
  });

    const serviceUserAccountsModel = Sequelize.define('serviceUserAccount', {
      // belongs to User
      
      id: { 
        type: DataTypes.INTEGER, 
        primaryKey: true, 
        autoIncrement: true 
      },

      display_name: {
        type: DataTypes.STRING,
        allowNull: true
      },

      email_address: {
        type: DataTypes.STRING,
        allowNull: true
      },
  
      service_id: { 
        type: DataTypes.SMALLINT,
        allowNull: true,
      },

      service_user_id: { 
        type: DataTypes.STRING,
        allowNull: true,
      },
  
      refresh_token: {
        type: DataTypes.STRING,
        allowNull: true
      },
  
      access_token: {
        type: DataTypes.STRING,
        allowNull: true
      },
  
      token_type: {
        type: DataTypes.STRING,
        allowNull: true
      },
  
      expiration_date: {
        type: DataTypes.INTEGER,
        allowNull: true
      },
  
      storage_limit: {
        type: DataTypes.INTEGER,
        allowNull: true
      },

      storage_usage: {
        type: DataTypes.INTEGER,
        allowNull: true
      },

      trashed_storage_usage: {
        type: DataTypes.INTEGER,
        allowNull: true
      },
      
    });

// Relations

module.exports = function( database ){
  const User = database.models.user.user;
  const ServiceUserAccounts = database.models.user.serviceUserAccounts;
  
  User.hasMany(ServiceUserAccounts);
  ServiceUserAccounts.belongsTo(User);
};

What do you expect to happen?

As it was working perfectly before with mysql dialect, I expect it to also work with Postgresql.

What is actually happening?

relation "serviceUserAccounts" does not exist. I’m able to run the query just fine in pgAdmin, so it must be something with sequelize. What am I missing?

Here’s the gist with the stacktrace
https://gist.github.com/Mk-Etlinger/569093387a0cb97699acfcba3994f59d

Any ideas? I checked my permissions and it came back public, $user.

also looked here but no luck:
https://stackoverflow.com/questions/28844617/sequelize-with-postgres-database-not-working-after-migration-from-mysql

https://stackoverflow.com/questions/946804/find-out-if-user-got-permission-to-select-update-a-table-function-in-pos

Dialect: postgres
Dialect version: XXX
Database version: 9.6.2
Sequelize version: ^4.38.1
Tested with latest release: Yes, 4.39.0

Note : Your issue may be ignored OR closed by maintainers if it’s not tested against latest version OR does not follow issue template.

Posted on Dec 24, 2021


When you’re running Sequelize code to fetch or manipulate data from a PostgreSQL database, you might encounter an error saying relation <table name> does not exist.

For example, suppose you have a database named User in your PostgreSQL database as shown below:

cakeDB=# dt

          List of relations
 Schema | Name | Type  |    Owner
--------+------+-------+-------------
 public | User | table | nsebhastian
(1 row)

In the above output from psql, the cakeDB database has one table named User that you need to retrieve the data using Sequelize findAll() method.

Next, you create a new connection to the database using Sequelize and create a model for the User table:

const { Sequelize } = require("sequelize");

const sequelize = new Sequelize("cakeDB", "nsebhastian", "", {
  host: "localhost",
  dialect: "postgres",
});

const User = sequelize.define("User", {
  firstName: {
    type: Sequelize.STRING,
  },
  lastName: {
    type: Sequelize.STRING,
  },
});

After that, you write the code to query the User table as follows:

const users = await User.findAll();
console.log(users);

Although the code above is valid, Node will throw an error as follows:

Error
    at Query.run
    ...
  name: 'SequelizeDatabaseError',
  parent: error: relation "Users" does not exist

In PostgreSQL, a relation does not exist error happens when you reference a table name that can’t be found in the database you currently connect to.

In the case above, the error happens because Sequelize is trying to find Users table with an s, while the existing table is named User without an s.

But why does Sequelize refer to Users while we clearly define User in our model above? You can see it in the code below:

const User = sequelize.define("User", {
  firstName: {
    type: Sequelize.STRING,
  },
  lastName: {
    type: Sequelize.STRING,
  },
});

This is because Sequelize automatically pluralizes the model name User as Users to find the table name in your database (reference here)

To prevent Sequelize from pluralizing the table name for the model, you can add the freezeTableName option and set it to true to the model as shown below:

const User = sequelize.define("User", {
  firstName: {
    type: Sequelize.STRING,
  },
  lastName: {
    type: Sequelize.STRING,
  },
},
{
  freezeTableName: true,
});

The freezeTableName option will cause Sequelize to infer the table name as equal to the model name without any modification.

Alternatively, you can also add the tableName option to tell Sequelize directly the table name for the model:

const User = sequelize.define("User", {
  firstName: {
    type: Sequelize.STRING,
  },
  lastName: {
    type: Sequelize.STRING,
  },
},
{
  tableName: "User",
});

Once you add one of the two options above, this error should be resolved.

Please note that the model and table names in Sequelize and PostgreSQL are also case-sensitive, so if you’re table name is User, you will trigger the error when you refer to it as user from Sequelize:

const User = sequelize.define("User", {
  firstName: {
    type: Sequelize.STRING,
  },
  lastName: {
    type: Sequelize.STRING,
  },
},
{
  tableName: "user", // relation "user" does not exist
});

The relation does not exist error in Sequelize always happens when you refer to a PostgreSQL database table that doesn’t exist.

When you encounter this error, the first thing to check is to make sure that the Sequelize code points to the right table name.

This error can also occur in your migration code because you might have migration files that create a relationship between two tables.

Always make sure that you’re referencing the right table, and that you’re using the right letter casing.

Содержание

  1. Debugging “relation does not exist” error in postgres
  2. PostgreSQL relation «mytable» does not exist #1044
  3. Comments
  4. sergioszy commented Dec 16, 2017
  5. Environment
  6. brettwooldridge commented Dec 16, 2017
  7. sergioszy commented Dec 16, 2017
  8. org.postgresql.util.PSQLException:ERROR: relation «contacts» does not exist
  9. Comments

Debugging “relation does not exist” error in postgres

So, i was getting this nasty error even when the table clearly existed in t11 database.

Even after lot of googling, debugging and trying Stackoverflow solutions, there was no resolution. Then i got a hunch, that i should check what database and schema were actually being used when done programmatically (even though dbname was clearly provided in connection string).

If you use database t11 by running c t11 and then run:

select * from information_schema.tables where table_schema NOT IN (‘pg_catalog’, ‘information_schema’)

It will tell you that userinfo5 does exist in t11 database. But what happens when we try to access it programmatically?

So, i ran above query in a golang function, the function which was earlier running query select * from userinfo5 where >

Output showed that database name which was actually being used was postgres and not t11 Why?

Because, my postgres user was configured to not use password. But my connection string had password= This was somehow confusing the DB driver and postgres database was being used and not t11 .

remove password= from connection string so that it looks like: “host=localhost port=5432 user=postgres dbname=t11 sslmode=disable”

  1. Alter user postgres so that it uses password: alter user postgres with password ‘pwd123’;
  2. Change connection string: “host=localhost port=5432 user=postgres password=pwd123 dbname=t11 sslmode=disable”

Источник

PostgreSQL relation «mytable» does not exist #1044

Environment

PreparedStatement prepared = connection.preparedStatement(
«select mytable.column1, mytable.column2 from mytable where mytable.column1 > 0» ); //OK

When execute resultSet = prepared.executeQuery();

throws this exception

org.postgresql.util.PSQLException: ERROR: relation mytable does not exist
Position: 176
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2190)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:117)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)

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

This is not a HikariCP question, this is a PostgreSQL question.

PostgreSQL will not throw an error on prepare, even if the relation does not exist, because the driver will not actually prepare the statement until it has been executed several times. Creating a Statement via Statement stmt = connection.createStatement() , and then executing the same query via resultSet = stmt.executeQuery(«select . «) will fail with the same error.

You may be connecting to PostgreSQL server, but you are not connecting to the database which contains that table. Either specifiy the database, or check that the user has permission to see that table.

But, if I use directly the PGSimpleDatasource everthing is OK. Then the problem is in how HikariCP

Источник

org.postgresql.util.PSQLException:ERROR: relation «contacts» does not exist

Hello, I am pretty new to java and NetBeans. I am getting an error that appears when NetBeans tries to insert a record into a PostgreSQL database. I am using the files that are from a Sun Java tutorial.
————————————-
insert into contacts(id, first_name, last_name)

org.postgresql.util.PSQLException: ERROR: relation «contacts» does not exist
————————————-
I think PostgreSQL needs a SQL statement to formatted like the following: «schema».»tablename»
To include parenthesis around the schema name followed by a dot, followed by the table name. But in the insert statement that NetBeans is creating, just includes the the table name. I have tried to modify the code in different ways, but I can’t get it to format the SQL statement correctly.

I have included the entire statement below. Thanks again for any help.

/**
* Updates the selected contact or inserts a new one (if we are
* in the insert mode).
*
* @param firstName first name of the contact.
* @param lastName last name of the contact.
* @param title title of the contact.
* @param nickname nickname of the contact.
* @param displayFormat display format for the contact.
* @param mailFormat mail format for the contact.
* @param emails email addresses of the contact.
*/
public void updateContact(String firstName, String lastName, String title, String nickname,
int displayFormat, int mailFormat, Object[] emails) <
int selection = getContactSelection().getMinSelectionIndex();
Statement stmt = null;
try <
if (!insertMode) <
rowSet.absolute(selection+1);
>
Connection con = rowSet.getConnection();
stmt = con.createStatement();
String sql;
if (insertMode) <
sql = «insert into public.» + CONTACTS_TABLE + «(» + CONTACTS_KEY + «, » + CONTACTS_FIRST_NAME + «, »
+ CONTACTS_LAST_NAME + «, » + CONTACTS_TITLE + «, » + CONTACTS_NICKNAME + «, »
+ CONTACTS_DISPLAY_FORMAT + «, » + CONTACTS_MAIL_FORMAT + «, » + CONTACTS_EMAIL_ADDRESSES
+ «) values ((case when (select max(» + CONTACTS_KEY + «) from » + CONTACTS_TABLE + «)»
+ «IS NULL then 1 else (select max(» + CONTACTS_KEY + «) from » + CONTACTS_TABLE + «)+1 end), »
+ encodeSQL(firstName) + «, » + encodeSQL(lastName) + «, » + encodeSQL(title) + «, »
+ encodeSQL(nickname) + «, » + displayFormat + «, » + mailFormat + «, »
+ encodeSQL(encodeEmails(emails)) + «)»;
> else <
sql = «update public.» + CONTACTS_TABLE + » set «;
sql += CONTACTS_FIRST_NAME + ‘=’ + encodeSQL(firstName) + «, «;
sql += CONTACTS_LAST_NAME + ‘=’ + encodeSQL(lastName) + «, «;
sql += CONTACTS_TITLE + ‘=’ + encodeSQL(title) + «, «;
sql += CONTACTS_NICKNAME + ‘=’ + encodeSQL(nickname) + «, «;
sql += CONTACTS_DISPLAY_FORMAT + ‘=’ + displayFormat + «, «;
sql += CONTACTS_MAIL_FORMAT + ‘=’ + mailFormat + «, «;
sql += CONTACTS_EMAIL_ADDRESSES + ‘=’ + encodeSQL(encodeEmails(emails));
sql += » where » + CONTACTS_KEY + ‘=’ + rowSet.getObject(CONTACTS_KEY);
>
System.out.println(sql);
stmt.executeUpdate(sql);
rowSet.execute();
> catch (SQLException sqlex) <
sqlex.printStackTrace();
> finally <
setInsertMode(false);
if (stmt != null) <
try <
stmt.close();
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
>
>
>

What’s that «encodeSQL» method doing? You’re much better off with a PreparedStatement, IMO.

No, you don’t need the «public.». Connect to the database and use the table name just as it appears in the Postgres client. That’s what I do. It works fine.

That’s the worst way you can possible build up that SQL statement. Why create all those extra Strings? Better to use a StringBuffer and PreparedStatement.

No transactional logic that I can see. Wouldn’t you want the INSERT to rollback if an exception is caught?

The writeable row set must be a data member of this class. You’ve done nothing to synchronize this method, so it’s not thread safe. Don’t use it with more than one client.

Thanks for your reply.

Knowing that I don’t need the «public» schema keyword helps, but I think I still need the » » double quotes around the table name?

Below is the entire code. Does this look thread safe or like it has any transaction logic?

import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

/**
* Model of Contacts application.
*
* @author Jan Stola
*/
public class ContactsModel implements ListSelectionListener <
// Constants for database objects
private static final String CONTACTS_TABLE = «contacts»;
private static final String CONTACTS_KEY = «id»;
private static final String CONTACTS_ID = «id»;
private static final String CONTACTS_FIRST_NAME = «first_name»;
private static final String CONTACTS_LAST_NAME = «last_name»;
private static final String CONTACTS_TITLE = «title»;
private static final String CONTACTS_NICKNAME = «nickname»;
private static final String CONTACTS_DISPLAY_FORMAT = «display_format»;
private static final String CONTACTS_MAIL_FORMAT = «mail_format»;
private static final String CONTACTS_EMAIL_ADDRESSES = «email_addresses»;

// Constants for property names
public static final String PROP_REMOVAL_ENABLED = «removalEnabled»;
public static final String PROP_EDITING_ENABLED = «editingEnabled»;

// RowSet with contacts
private JDBCRowSet rowSet;
// Contacts selection model
private ListSelectionModel contactSelection;
// Insert mode (e.g. are we about to insert a new contact)
private boolean insertMode;

/**
* Getter for rowSet property.
*
* @return rowSet with contacts.
*/
public JDBCRowSet getRowSet() <
return rowSet;
>

/**
* Setter for rowSet property.
*
* @param rowSet rowSet with contacts.
*/
public void setRowSet(JDBCRowSet rowSet) <
this.rowSet = rowSet;
>

/**
* Getter for contactSelection property.
*
* @return contacts selection model.
*/
public ListSelectionModel getContactSelection() <
if (contactSelection == null) <
contactSelection = new DefaultListSelectionModel();
contactSelection.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setContactSelection(contactSelection);
>
return contactSelection;
>

/**
* Setter for contactSelection property.
*
* @param contactSelection contacts selection model.
*/
public void setContactSelection(ListSelectionModel contactSelection) <
if (this.contactSelection != null) <
this.contactSelection.removeListSelectionListener(this);
>
this.contactSelection = contactSelection;
contactSelection.addListSelectionListener(this);
>

/**
* Setter for insertMode property.
*
* @param insertMode insert mode.
*/
void setInsertMode(boolean insertMode) <
this.insertMode = insertMode;
>

/**
* Returns ID of the selected contact.
*
* @return ID of the selected contact.
*/
public String getID() <
return insertMode ? null : stringValue(CONTACTS_ID);
>

/**
* Returns the first name of the selected contact.
*
* @return the first name of the selected contact.
*/
public String getFirstName() <
return insertMode ? «» : stringValue(CONTACTS_FIRST_NAME);
>

/**
* Returns the last name of the selected contact.
*
* @return the last name of the selected contact.
*/
public String getLastName() <
return insertMode ? «» : stringValue(CONTACTS_LAST_NAME);
>

/**
* Returns title of the selected contact.
*
* @return title of the selected contact.
*/
public String getTitle() <
return insertMode ? «» : stringValue(CONTACTS_TITLE);
>

/**
* Returns nickname of the selected contact.
*
* @return nickname of the selected contact.
*/
public String getNickname() <
return insertMode ? «» : stringValue(CONTACTS_NICKNAME);
>

/**
* Returns display format of the selected contact.
*
* @return display format of the selected contact.
*/
public int getDisplayFormat() <
return insertMode ? 0 : intValue(CONTACTS_DISPLAY_FORMAT);
>

/**
* Returns mail format of the selected contact.
*
* @return mail format of the selected contact.
*/
public int getMailFormat() <
return insertMode ? 0 : intValue(CONTACTS_MAIL_FORMAT);
>

/**
* Returns email addresses of the selected contact.
*
* @return email addresses of the selected contact.
*/
public Object[] getEmails() <
String encodedEmails = insertMode ? null : stringValue(CONTACTS_EMAIL_ADDRESSES);
return decodeEmails(encodedEmails);
>

/**
* Determines whether editing of the selected contact is enabled.
*
* @return true if the selected contact can be edited,
* returns false otherwise.
*/
public boolean isEditingEnabled() <
// Additional business logic can go here
return (getContactSelection().getMinSelectionIndex() != -1);
>

/**
* Determines whether removal of the selected contact is enabled.
*
* @return true if the selected contact can be removed,
* returns false otherwise.
*/
public boolean isRemovalEnabled() <
// Additional business logic can go here
return (getContactSelection().getMinSelectionIndex() != -1);
>

// Helper method that returns value of a selected contact’s attribute
private String stringValue(String columnName) <
String value = null;
try <
if ((rowSet != null) && selectContactInRowSet()) <
value = rowSet.getString(columnName);
>
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
return value;
>

// Helper method that returns value of a selected contact’s attribute
private int intValue(String columnName) <
int value = 0;
try <
if ((rowSet != null) && selectContactInRowSet()) <
value = rowSet.getInt(columnName);
>
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
return value;
>

// Helper method that synchronizes rowSet position with selected contact
private boolean selectContactInRowSet() <
int index = getContactSelection().getMinSelectionIndex();
if (index != -1) <
try <
rowSet.absolute(index+1);
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
>
return (index != -1);
>

// Helper method that decodes email addresses from the encoded string
private Object[] decodeEmails(String encodedEmails) <
if ((encodedEmails == null) || (encodedEmails.equals(«»))) <
return new String[0];
>
char sep = encodedEmails.charAt(0);
List emails = new LinkedList();
StringTokenizer st = new StringTokenizer(encodedEmails, String.valueOf(sep));
while (st.hasMoreTokens()) <
emails.add(st.nextToken());
>
return emails.toArray(new Object[emails.size()]);
>

// Helper method that encodes email addresses into one string
private String encodeEmails(Object[] emails) <
StringBuffer sb = new StringBuffer();
for (int i=0; i 0 · Share on Twitter Share on Facebook

Источник

Понравилась статья? Поделить с друзьями:
  • Psql error could not connect to server fatal role postgres does not exist
  • Psp ошибка 80431075
  • Psp ошибка 80020148 как исправить
  • Psp 3008 ошибка чтения диска
  • Pso2 error 650