如果我理解正确,您想选择并查看表格内容,然后能够将其导出到您计算机上的文件中吗?
如果是这样,我会这样做:
1) 首先导入我需要的函数(在我的例子中我使用 MSSQL)
const sql = require('mssql');
const fs = require('fs');
我使用 MSSQL 进行数据库管理,所以在这种情况下,我需要导入 MSSQL 才能连接和查询我的数据库。
FS(或“文件系统”)包含将文件从某个文件位置复制到另一个位置的功能。
2) 然后我将配置我的数据库连接:
var config =
{
user: 'your username to log in',
password: 'password to log in',
server: "server path",
database: 'name of the database',
connectionTimeout: 0,
requestTimeout: 0,
pool:{
idleTimeoutMillis: 500,
max: 1
}
};
3)然后我将开始制作我的功能,其中包括文件的查询和保存:
function commenceQuery()
{
var connection = new sql.ConnectionPool(config);
var request = new sql.Request(connection);
request.query("DECLARE @output removableTable (id INT IDENTITY, command NVARCHAR(512)) DECLARE @query = 'SELECT * FROM yourTable', @outputFile = VARCHAR (2048) = 'Where you want the file to be saved, most probably will be on the database computer', @connectionString VARCHAR = '-U databaseUserName -P databasePassword' + @@servername, @bcpQuery = 'bcp "@query" QUERYOUT "@outputFile" -T -c -t, -r\n @connectionString' SET @bcpQuery = REPLACE (@bcpQuery, '@query', @query) SET @bcpQuery = REPLACE (@bcpQuery, '@outputFile', @outputFile+'Test_Name.csv') SET @bcpQuery = REPLACE (@bcpQuery, '@connectionString', @connectionString) SET @bcpQuery = REPLACE (@bcpQuery, CHAR(10), ' ')) INSERT INTO @output EXEC master..xp cmdshell @bcpquery")
.then(function()
{
fs.copyFile('/filePath/to/where/output/isSpecified', '/filePath/of/where/you/want/toSave')
}
.catch(function()
{
conn.close()
})
};
详细解释我在 request.query('') 中陈述的查询:
DECLARE @output removableTable (id INT IDENTITY, command
NVARCHAR(512))
声明一个类似于临时表的变量,将收集到的信息放入其中
DECLARE @query = 'SELECT * FROM yourTable'
声明一个变量来保存实际的查询字符串
@outputFile = VARCHAR (2048) = 'Where you want the file to be saved,
most probably will be on the database computer'
声明一个变量来保存数据库应该输出文件的文件路径目标,例如:C:\Program Files\anyFolder
@connectionString VARCHAR = '-U databaseUserName -P databasePassword' + @@servername
和我们上面使用的配置一样,它是登录数据库本身的关键。
@bcpQuery = 'bcp "@query" QUERYOUT "@outputFile" -T -c -t, -r\n
@connectionString'
我们将使用它作为一种执行方式,将具有“@”的变量替换为实际值(在下面声明)
SET @bcpQuery = REPLACE (@bcpQuery, '@query', @query)
将 @query 替换为它包含的字符串
SET @bcpQuery = REPLACE (@bcpQuery, '@outputFile',
@outputFile+'Test_Name.csv')
同上
SET @bcpQuery = REPLACE (@bcpQuery, '@connectionString',
@connectionString)
同上
SET @bcpQuery = REPLACE (@bcpQuery, CHAR(10), ' '))
删除任何换行符
INSERT INTO @output
将您收到的所有内容插入@output
EXEC master..xp cmdshell @bcpquery
在 cmdshell 中执行整个查询
希望这会有所帮助!如果您遇到问题,请告诉我