
打开 IDEA,选择“Create New Project”创建一个新的 Node.js 项目。
在新建项目的目录下打开终端,使用 npm 命令安装 mysql 模块,命令如下:
css
Copy code
npm install mysql --save
在项目的根目录下创建一个名为 index.js 的文件,编写以下代码:
javascript
Copy code
const mysql = require('mysql')
// 创建连接对象
const connection = mysql.createConnection({
host: 'localhost', // 数据库服务器地址
user: 'root', // 数据库用户名
password: 'password', // 数据库密码
database: 'test', // 数据库名称
port: 3306 // 数据库端口号,默认为 3306
})
// 连接数据库
connection.connect()
// 执行 SQL 查询语句
connection.query('SELECT * FROM user', function (error, results, fields) {
if (error) throw error
console.log('The solution is: ', results)
})
// 关闭连接
connection.end()
其中,需要将 host、user、password、database 等参数设置为实际的数据库连接信息。
在终端中运行 index.js 文件,命令如下:
Copy code
node index.js
这样,就可以连接到 MySQL 数据库,并查询指定的表中的数据。
以上是使用 Node.js 连接 MySQL 数据库的简单示例,如果需要进行更复杂的 *** 作,可以参考 mysql 模块的文档,了解更多的 API 和用法。
通常在NodeJS开发中我们经常涉及到 *** 作数据库,尤其是 MySQL ,作为应用最为广泛的开源数据库则成为我们的首选,本篇就来介绍下如何通过NodeJS来 *** 作 MySQL 数据库。 安装MySQL模块到NodeJS中 我们需要让NodeJS支持MySQL,则需要将MySQL模块添加到系统支持库想要快速了解Node.js ,赞生推荐亲看看 node.js_guide.pdf — node.js 开发指南 :想要电子版高清的 留言发送
如果不想留言 可以带你做飞机! 直接下载
Node.js
简单介绍一下node.js的 *** 作吧
安装 node-mysql
$ npm install mysql
创建测试表
//数据库名 NodeSampleCREATE TABLE `NodeSample`.`MyTable` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`firstname` VARCHAR( 20 ) NOT NULL ,
`lastname` VARCHAR( 20 ) NOT NULL ,
`message` TEXT NOT NULL
) ENGINE = MYISAM
连接数据库
Js代码
var sys = require('sys')
var Client = require('mysql').Client
var client = new Client()
client.user = 'someuser'
client.password = 'password'
client.connect(function(error, results) {
if(error) {
console.log('Connection Error: ' + error.message)
return
}
console.log('Connected to MySQL')
})
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)