-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4aaf9bf
commit e84d5eb
Showing
6 changed files
with
838 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import { Client as PgClient } from 'pg'; // PostgreSQL 客户端 | ||
import mysql from 'mysql2/promise'; // MySQL 客户端 | ||
|
||
type Props = { | ||
databaseType: string; | ||
host: string; | ||
port: string; | ||
databaseName: string; | ||
user: string; | ||
password: string; | ||
sql: string; | ||
}; | ||
|
||
type Response = Promise<{ | ||
result: any; // 根据你的 SQL 查询结果类型调整 | ||
}>; | ||
|
||
const main = async ({ | ||
databaseType, | ||
host, | ||
port, | ||
databaseName, | ||
user, | ||
password, | ||
sql | ||
}: Props): Response => { | ||
let result; | ||
|
||
try { | ||
if (databaseType === 'PostgreSQL') { | ||
const client = new PgClient({ | ||
host, | ||
port: parseInt(port, 10), | ||
database: databaseName, | ||
user, | ||
password | ||
}); | ||
|
||
await client.connect(); | ||
const res = await client.query(sql); | ||
result = res.rows; | ||
await client.end(); | ||
} else if (databaseType === 'MySQL') { | ||
const connection = await mysql.createConnection({ | ||
host, | ||
port: parseInt(port, 10), | ||
database: databaseName, | ||
user, | ||
password | ||
}); | ||
|
||
const [rows] = await connection.execute(sql); | ||
result = rows; | ||
await connection.end(); | ||
} | ||
return { | ||
result | ||
}; | ||
} catch (error: unknown) { | ||
// 使用类型断言来处理错误 | ||
if (error instanceof Error) { | ||
console.error('Database query error:', error.message); | ||
throw new Error(error.message); | ||
} else { | ||
console.error('Database query error:', error); | ||
throw new Error('An unknown error occurred'); | ||
} | ||
} | ||
}; | ||
|
||
export default main; |
Oops, something went wrong.