是否有可能将postgreSQL直接连接到Javascript?

时间:2011-02-17 13:10:09

标签: javascript postgresql

无需使用php,python或odbc?

7 个答案:

答案 0 :(得分:12)

您可以从https://github.com/creationix/postgres-js

获取Postgres的JS驱动程序

这个设计用于node.js.不要指望能够在Web浏览器中找到可以在客户端运行的东西。

答案 1 :(得分:3)

不,请记住,只有在浏览器中使用时,Javascript才能在客户端工作,而数据库只能从服务器端连接。因此,您需要使用PHP,Python或其他服务器端语言调用服务器端脚本才能获得结果。

答案 2 :(得分:3)

是的,如果你的javascript在node.js上运行是可能的。这是connector

答案 3 :(得分:3)

我使用过Postgrest(postgrest.com)。

" PostgREST是一个独立的Web服务器,可以将您的PostgreSQL数据库直接转换为RESTful API。"

然后你可以用一个以json格式返回数据的url进行查询。

答案 4 :(得分:2)

我从未使用PostgreSQL,但据我所知,数据库需要有效的凭据(用户名和密码)来访问它们。 使用JavaScript,您无法隐藏用户名和密码,因为脚本已发送到客户端。理论上,如果你能做到这一点,任何客户都可以运行查询,并为数据库做任何他们想做的事。

无论如何,您无法从客户端访问数据库。

答案 5 :(得分:1)

有可能。请参阅以下代码。在使用之前,您应该将Node.js更新为7.6.0或更高版本。您只能通过调用Postgresql函数来使用main(yourQuery)。在Google上找到它。

const pg = require('pg')

// create a config to configure both pooling behavior
// and client options
// note: all config is optional and the environment variables
// will be read if the config is not present
var config = {
    user: 'username', // env var: PGUSER
    database: 'databaseName', // env var: PGDATABASE
    password: 'Password', // env var: PGPASSWORD
    host: 'localhost', // Server hosting the postgres database
    port: 35432, // env var: PGPORT
    max: 10, // max number of clients in the pool
    idleTimeoutMillis: 30000 // how long a client is allowed to remain idle before being closed
}


const pool = new pg.Pool(config)

async function query (q) {
    const client = await pool.connect()
    let res
    try {
        await client.query('BEGIN')
        try {
            res = await client.query(q)
            await client.query('COMMIT')
        } catch (err) {
            await client.query('ROLLBACK')
            throw err
        }
    } finally {
        client.release()
    }
    return res
}

async function main (queryStr) {
    try {
        const { rows } = await query(queryStr);
        console.log(JSON.stringify(rows));
    } catch (err) {
        console.log('Database ' + err)
    }
}
main('SELECT * FROM user where user = \'123\'') 

答案 6 :(得分:-4)

不。 Javascript只是客户端。您需要某种服务器端语言/接口。