开发者

Is there a possibility of connecting postgreSQL directly to Javascript?

开发者_StackOverflow

without having to use php, python or odbc?


You can get a JS driver for Postgres from https://github.com/creationix/postgres-js

This one is designed for use with node.js. Don't expect to be able to find something you can run client side in a web browser.


I have used Postgrest (postgrest.com).

"PostgREST is a standalone web server that turns your PostgreSQL database directly into a RESTful API."

Then you can make a query with a url which returns data in json format.


No, keep in mind that Javascript works client side only when used in a browser while a database can only be connected from server side. Thus you will need to call a serverside script in PHP, Python or another server-side language in order to get to the results.


Yes, it is possible if your javascript runs on node.js. Here is connector.


I never worked with PostgreSQL, but as far as I know Databases require a valid credentials (username and password) to access them. With JavaScript you have no way of hiding the username and password, as the script is sent to the client. So theoretically if you could do that, any client would be able to run queries, and do whatever they want with your database.

Anyways, you cannot access a database from the client side.


It is possible. Please see following code. Before using it, you should update Node.js to 7.6.0 or higher. You can use Postgresql by calling only main(yourQuery) function. Found it on 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\'') 


Nope. Javascript is client-side only. You need some sort of server-side language/interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜