Nodejs连接postgres或mysql

本文介绍如何在Node.js中安装并使用mysql和pg(PostgreSQL)数据库访问模块,包括具体的文件结构、依赖关系及示例代码。

安装数据库访问模块

 npm install pg  

 npm install mysql

这样在这些模块安装在当前目录的node_modules子目录

tree node_modules/

├── mysql
│   ├── Changes.md
│   ├── index.js
│   ├── lib
│   │   ├── ConnectionConfig.js
│   │   ├── Connection.js
│   │   ├── PoolCluster.js
│   │   ├── PoolConfig.js
│   │   ├── PoolConnection.js
│   │   ├── Pool.js
│   │   ├── PoolNamespace.js
│   │   ├── PoolSelector.js
│   │   └── protocol
│   │       ├── Auth.js
│   │       ├── constants
│   │       │   ├── charsets.js
│   │       │   ├── client.js
│   │       │   ├── errors.js
│   │       │   ├── field_flags.js
│   │       │   ├── server_status.js
│   │       │   ├── ssl_profiles.js
│   │       │   └── types.js
│   │       ├── PacketHeader.js
│   │       ├── packets
│   │       │   ├── ClientAuthenticationPacket.js
│   │       │   ├── ComChangeUserPacket.js
│   │       │   ├── ComPingPacket.js
│   │       │   ├── ComQueryPacket.js
│   │       │   ├── ComQuitPacket.js
│   │       │   ├── ComStatisticsPacket.js
│   │       │   ├── EmptyPacket.js
│   │       │   ├── EofPacket.js
│   │       │   ├── ErrorPacket.js
│   │       │   ├── Field.js
│   │       │   ├── FieldPacket.js
│   │       │   ├── HandshakeInitializationPacket.js
│   │       │   ├── index.js
│   │       │   ├── LocalDataFilePacket.js
│   │       │   ├── OkPacket.js
│   │       │   ├── OldPasswordPacket.js
│   │       │   ├── ResultSetHeaderPacket.js
│   │       │   ├── RowDataPacket.js
│   │       │   ├── SSLRequestPacket.js
│   │       │   ├── StatisticsPacket.js
│   │       │   └── UseOldPasswordPacket.js
│   │       ├── PacketWriter.js
│   │       ├── Parser.js
│   │       ├── Protocol.js
│   │       ├── ResultSet.js
│   │       ├── sequences
│   │       │   ├── ChangeUser.js
│   │       │   ├── Handshake.js
│   │       │   ├── index.js
│   │       │   ├── Ping.js
│   │       │   ├── Query.js
│   │       │   ├── Quit.js
│   │       │   ├── Sequence.js
│   │       │   └── Statistics.js
│   │       └── SqlString.js
│   ├── License
│   ├── node_modules
│   │   ├── bignumber.js
│   │   │   ├── bignumber.js
│   │   │   ├── bignumber.js.map
│   │   │   ├── bignumber.min.js
│   │   │   ├── bower.json
│   │   │   ├── doc
│   │   │   │   └── API.html
│   │   │   ├── LICENCE
│   │   │   ├── package.json
│   │   │   └── README.md
│   │   └── readable-stream
│   │       ├── duplex.js
│   │       ├── float.patch
│   │       ├── lib
│   │       │   ├── _stream_duplex.js
│   │       │   ├── _stream_passthrough.js
│   │       │   ├── _stream_readable.js
│   │       │   ├── _stream_transform.js
│   │       │   └── _stream_writable.js
│   │       ├── LICENSE
│   │       ├── node_modules
│   │       │   ├── core-util-is
│   │       │   │   ├── float.patch
│   │       │   │   ├── lib
│   │       │   │   │   └── util.js
│   │       │   │   ├── LICENSE
│   │       │   │   ├── package.json
│   │       │   │   ├── README.md
│   │       │   │   └── test.js
│   │       │   ├── inherits
│   │       │   │   ├── inherits_browser.js
│   │       │   │   ├── inherits.js
│   │       │   │   ├── LICENSE
│   │       │   │   ├── package.json
│   │       │   │   ├── README.md
│   │       │   │   └── test.js
│   │       │   ├── isarray
│   │       │   │   ├── build
│   │       │   │   │   └── build.js
│   │       │   │   ├── component.json
│   │       │   │   ├── index.js
│   │       │   │   ├── package.json
│   │       │   │   └── README.md
│   │       │   └── string_decoder
│   │       │       ├── index.js
│   │       │       ├── LICENSE
│   │       │       ├── package.json
│   │       │       └── README.md
│   │       ├── package.json
│   │       ├── passthrough.js
│   │       ├── readable.js
│   │       ├── README.md
│   │       ├── transform.js
│   │       └── writable.js
│   ├── package.json
│   └── Readme.md
└── pg
    ├── lib
    │   ├── client.js
    │   ├── connection.js
    │   ├── connection-parameters.js
    │   ├── defaults.js
    │   ├── index.js
    │   ├── native
    │   │   ├── index.js
    │   │   ├── query.js
    │   │   └── result.js
    │   ├── pool.js
    │   ├── query.js
    │   ├── result.js
    │   ├── type-overrides.js
    │   └── utils.js
    ├── Makefile
    ├── NEWS.md
    ├── node_modules
    │   ├── buffer-writer
    │   │   ├── benchmark
    │   │   │   ├── index.js
    │   │   │   ├── int-16-benchmark.js
    │   │   │   ├── int-32-benchmark.js
    │   │   │   ├── join-benchmark.js
    │   │   │   ├── resize-benchmark.js
    │   │   │   └── small-benchmark.js
    │   │   ├── index.js
    │   │   ├── LICENSE
    │   │   ├── package.json
    │   │   ├── README.md
    │   │   └── test
    │   │       ├── mocha.opts
    │   │       └── writer-tests.js
    │   ├── generic-pool
    │   │   ├── fabfile.py
    │   │   ├── lib
    │   │   │   └── generic-pool.js
    │   │   ├── Makefile
    │   │   ├── package.json
    │   │   ├── README.md
    │   │   └── test
    │   │       └── generic-pool.test.js
    │   ├── packet-reader
    │   │   ├── index.js
    │   │   ├── package.json
    │   │   └── test
    │   │       └── index.js
    │   ├── pg-connection-string
    │   │   ├── index.js
    │   │   ├── LICENSE
    │   │   ├── package.json
    │   │   ├── README.md
    │   │   └── test
    │   │       └── parse.js
    │   ├── pgpass
    │   │   ├── lib
    │   │   │   ├── helper.js
    │   │   │   └── index.js
    │   │   ├── node_modules
    │   │   │   └── split
    │   │   │       ├── examples
    │   │   │       │   └── pretty.js
    │   │   │       ├── index.js
    │   │   │       ├── LICENCE
    │   │   │       ├── node_modules
    │   │   │       │   └── through
    │   │   │       │       ├── index.js
    │   │   │       │       ├── LICENSE.APACHE2
    │   │   │       │       ├── LICENSE.MIT
    │   │   │       │       ├── package.json
    │   │   │       │       ├── readme.markdown
    │   │   │       │       └── test
    │   │   │       │           ├── async.js
    │   │   │       │           ├── auto-destroy.js
    │   │   │       │           ├── buffering.js
    │   │   │       │           ├── end.js
    │   │   │       │           └── index.js
    │   │   │       ├── package.json
    │   │   │       ├── readme.markdown
    │   │   │       └── test
    │   │   │           ├── options.asynct.js
    │   │   │           ├── partitioned_unicode.js
    │   │   │           ├── split.asynct.js
    │   │   │           └── try_catch.asynct.js
    │   │   ├── package.json
    │   │   ├── README.md
    │   │   └── test
    │   │       ├── #1 de-escaping.js
    │   │       ├── #1 escaping.js
    │   │       ├── helper.js
    │   │       ├── index.js
    │   │       ├── integration
    │   │       │   └── #1 escaping.js
    │   │       └── _pgpass
    │   ├── pg-types
    │   │   ├── index.js
    │   │   ├── lib
    │   │   │   ├── arrayParser.js
    │   │   │   ├── binaryParsers.js
    │   │   │   └── textParsers.js
    │   │   ├── Makefile
    │   │   ├── node_modules
    │   │   │   ├── ap
    │   │   │   │   ├── examples
    │   │   │   │   │   └── z.js
    │   │   │   │   ├── index.js
    │   │   │   │   ├── package.json
    │   │   │   │   ├── README.markdown
    │   │   │   │   └── test
    │   │   │   │       └── curry.js
    │   │   │   ├── postgres-array
    │   │   │   │   ├── index.js
    │   │   │   │   ├── package.json
    │   │   │   │   └── readme.md
    │   │   │   ├── postgres-bytea
    │   │   │   │   ├── index.js
    │   │   │   │   ├── package.json
    │   │   │   │   └── readme.md
    │   │   │   ├── postgres-date
    │   │   │   │   ├── index.js
    │   │   │   │   ├── package.json
    │   │   │   │   └── readme.md
    │   │   │   └── postgres-interval
    │   │   │       ├── index.js
    │   │   │       ├── node_modules
    │   │   │       │   └── xtend
    │   │   │       │       ├── immutable.js
    │   │   │       │       ├── LICENCE
    │   │   │       │       ├── Makefile
    │   │   │       │       ├── mutable.js
    │   │   │       │       ├── package.json
    │   │   │       │       ├── README.md
    │   │   │       │       └── test.js
    │   │   │       ├── package.json
    │   │   │       └── readme.md
    │   │   ├── package.json
    │   │   ├── README.md
    │   │   └── test
    │   │       ├── index.js
    │   │       └── types.js
    │   └── semver
    │       ├── bin
    │       │   └── semver
    │       ├── foot.js.txt
    │       ├── head.js.txt
    │       ├── LICENSE
    │       ├── Makefile
    │       ├── package.json
    │       ├── README.md
    │       ├── semver.browser.js
    │       ├── semver.browser.js.gz
    │       ├── semver.js
    │       ├── semver.min.js
    │       ├── semver.min.js.gz
    │       └── test
    │           ├── amd.js
    │           ├── big-numbers.js
    │           ├── clean.js
    │           ├── gtr.js
    │           ├── index.js
    │           ├── ltr.js
    │           ├── major-minor-patch.js
    │           └── no-module.js
    ├── package.json
    ├── README.md
    ├── script
    │   ├── create-test-tables.js
    │   ├── dump-db-types.js
    │   ├── list-db-types.js
    │   └── test-connection.js
    └── test
        ├── buffer-list.js
        ├── cli.js
        ├── integration
        │   ├── client
        │   │   ├── api-tests.js
        │   │   ├── appname-tests.js
        │   │   ├── array-tests.js
        │   │   ├── big-simple-query-tests.js
        │   │   ├── cancel-query-tests.js
        │   │   ├── configuration-tests.js
        │   │   ├── custom-types-tests.js
        │   │   ├── empty-query-tests.js
        │   │   ├── error-handling-tests.js
        │   │   ├── force-native-with-envvar-tests.js
        │   │   ├── heroku.pgpass
        │   │   ├── heroku-pgpass-tests.js
        │   │   ├── heroku-ssl-tests.js
        │   │   ├── huge-numeric-tests.js
        │   │   ├── json-type-parsing-tests.js
        │   │   ├── no-data-tests.js
        │   │   ├── no-row-result-tests.js
        │   │   ├── notice-tests.js
        │   │   ├── parse-int-8-tests.js
        │   │   ├── prepared-statement-tests.js
        │   │   ├── query-callback-error-tests.js
        │   │   ├── query-column-names-tests.js
        │   │   ├── query-error-handling-prepared-statement-tests.js
        │   │   ├── query-error-handling-tests.js
        │   │   ├── quick-disconnect-tests.js
        │   │   ├── result-metadata-tests.js
        │   │   ├── results-as-array-tests.js
        │   │   ├── row-description-on-results-tests.js
        │   │   ├── simple-query-tests.js
        │   │   ├── ssl-tests.js
        │   │   ├── test-helper.js
        │   │   ├── timezone-tests.js
        │   │   ├── transaction-tests.js
        │   │   ├── type-coercion-tests.js
        │   │   └── type-parser-override-tests.js
        │   ├── connection
        │   │   ├── bound-command-tests.js
        │   │   ├── copy-tests.js
        │   │   ├── notification-tests.js
        │   │   ├── query-tests.js
        │   │   └── test-helper.js
        │   ├── connection-pool
        │   │   ├── double-connection-tests.js
        │   │   ├── ending-empty-pool-tests.js
        │   │   ├── ending-pool-tests.js
        │   │   ├── error-tests.js
        │   │   ├── idle-timeout-tests.js
        │   │   ├── max-connection-tests.js
        │   │   ├── optional-config-tests.js
        │   │   ├── single-connection-tests.js
        │   │   ├── test-helper.js
        │   │   └── waiting-connection-tests.js
        │   ├── domain-tests.js
        │   ├── gh-issues
        │   │   ├── 130-tests.js
        │   │   ├── 131-tests.js
        │   │   ├── 199-tests.js
        │   │   ├── 507-tests.js
        │   │   ├── 600-tests.js
        │   │   ├── 675-tests.js
        │   │   ├── 699-tests.js
        │   │   ├── 787-tests.js
        │   │   ├── 882-tests.js
        │   │   └── 981-tests.js
        │   └── test-helper.js
        ├── native
        │   ├── callback-api-tests.js
        │   ├── connection-tests.js
        │   ├── error-tests.js
        │   ├── evented-api-tests.js
        │   ├── missing-native.js
        │   └── stress-tests.js
        ├── test-buffers.js
        ├── test-helper.js
        └── unit
            ├── client
            │   ├── cleartext-password-tests.js
            │   ├── configuration-tests.js
            │   ├── connection-string-tests.js
            │   ├── early-disconnect-tests.js
            │   ├── escape-tests.js
            │   ├── md5-password-tests.js
            │   ├── notification-tests.js
            │   ├── prepared-statement-tests.js
            │   ├── query-queue-tests.js
            │   ├── result-metadata-tests.js
            │   ├── simple-query-tests.js
            │   ├── stream-and-query-error-interaction-tests.js
            │   └── test-helper.js
            ├── connection
            │   ├── error-tests.js
            │   ├── inbound-parser-tests.js
            │   ├── outbound-sending-tests.js
            │   ├── startup-tests.js
            │   └── test-helper.js
            ├── connection-parameters
            │   ├── creation-tests.js
            │   └── environment-variable-tests.js
            ├── pool
            │   ├── basic-tests.js
            │   └── timeout-tests.js
            ├── test-helper.js
            └── utils-tests.js

上面有很多例子可供参考:

实例

var pg = require('pg');  

//创建连接  
var conString = "postgres://y-user:y-ps@localhost:5432/y-db";  //postgres可改为tcp
var client = new pg.Client(conString);  

client.connect();

var query = client.query("select * from student");  //y-db有个student表
query.on('row',function(row){
    console.log(row);
    console.log("student name:%s",row.sname); //student表有个sname列
     });
 
query.on('end',function(){
    client.end();  
  }  
);

mysql的也差不多,不再举例

转载于:https://my.oschina.net/u/2245781/blog/664727

### Node.js 连接和操作 MySQL 数据库的插件 对于 Node.js 应用程序来说,有多个流行的插件可以用于连接和操作 MySQL 数据库。 #### 1. `mysql` 模块 这是最常用的官方模块之一,提供了轻量级且易于使用的 API 来访问 MySQL 数据库。它支持基本查询、预处理语句以及事务等功能[^2]。 ```javascript const mysql = require('mysql'); let connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db' }); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); }); connection.end(); ``` #### 2. `mysql2` 模块 作为 `mysql` 的升级版本,增加了对 Promise 和流的支持,性能更好,在大型项目中有更广泛的应用场景[^3]。 ```javascript const mysql = require('mysql2/promise'); async function main(){ const connection = await mysql.createConnection({/* ... */}); let [rows,fields] = await connection.execute( 'SELECT * FROM users WHERE id = ?', [1] ); } main().catch(console.error); ``` #### 3. Sequelize ORM Sequelize 是一个基于 promise 的 ORM(对象关系映射),不仅限于 MySQL,还兼容其他多种 SQL 数据库引擎。通过定义模型来简化数据表的操作过程[^4]。 ```javascript const { Sequelize } = require('sequelize'); // 创建一个新的 Sequelize 实例 const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */ }); class User extends Model {} User.init({ username: DataTypes.STRING, birthday: DataTypes.DATE }, {sequelize, modelName:'user'}); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值