【问题标题】:How do I check if a table exists? [duplicate]如何检查表是否存在? [复制]
【发布时间】:2017-09-30 16:25:35
【问题描述】:

在 db/index.js 中:

const { Pool } = require('pg'); //node-postgres
const pool = new Pool;

module.exports = {
    query: (text, params, callback) => {
        return pool.query(text,params,callback);
    }
};

在我的 main.js 中:

const db = require('./db/index');

    db.query('SELECT count(*) from pg_class where relname ="session" and relkind="r"', (err, res) => {
        if (err) {
          //TODO: What to do if there is an error?
        }
        console.log(res);
    });

输出是:

未定义

如何检查名称为“session”的表是否存在?我怎么知道我的查询是否有效?

编辑:这不是上述问题的重复,因为我的问题与 Node.js javascript 代码有关。不是 SQL!我只想知道在 res 对象中寻找什么,因为它似乎是未定义的......

【问题讨论】:

  • 大声喊她的名字,如果得到回答 - 桌子就在那里。
  • 建议您编辑标题,因为它具有误导性。

标签: node.js postgresql node-postgres


【解决方案1】:

您可以查看以下代码;

SELECT EXISTS (
   SELECT 1
   FROM   information_schema.tables 
   WHERE  table_schema = 'schema_name'
   AND    table_name = 'table_name'
   );

SELECT EXISTS (
   SELECT 1 
   FROM   pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   );

SELECT 'schema_name.table_name'::regclass

SELECT to_regclass('schema_name.table_name');

如果不存在此查询返回 null

【讨论】:

  • 如何检查 node.js 代码中的响应?我怎么知道架构名称是什么?我所做的只是创建一个表..
猜你喜欢
  • 2012-07-20
  • 2011-03-30
  • 2012-03-17
  • 2018-09-27
  • 1970-01-01
  • 2018-01-31
  • 2016-03-06
  • 2016-01-28
  • 2021-03-08
相关资源
最近更新 更多