Как написать функцию на js для работы с mysql
Вот код
const mysql = require('mysql');
const connection = mysql.createConnection({host: "host", user: "user", database: "database", password: "password"});
function select__sql(sql){
connection.connect();
try{
connection.query(sql, result => {
return 'This is result: ', result;
});
} finally {
connection.end();
}
}
console.log(select__sql('SELECT * FROM tablename'));
И я не понимаю почему совершается вывод indefind, хотя по теории должен совершиться вывод массива с данными
Новая версия кода
function select__sql(sql){
connection.connect();
try{
var results = connection.query(sql, function (error, results, fields){
});
return results;
} finally {
connection.end();
}
}
console.log(select__sql('SELECT * FROM tablename'));
И теперь у меня вот такой вывод
Query {
_events:
[Object: null prototype] {
error: [Function],
packet: [Function],
timeout: [Function],
end: [Function] },
_eventsCount: 4,
_maxListeners: undefined,
_callback: [Function],
_callSite:
Error
at Protocol._enqueue (/home/v1nc3nt_one1ll/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Connection.query (/home/v1nc3nt_one1ll/node_modules/mysql/lib/Connection.js:198:25)
at select__sql (/home/v1nc3nt_one1ll/Desktop/Template by/sql.js:49:42)
at Object.<anonymous> (/home/v1nc3nt_one1ll/Desktop/Template by/sql.js:58:13)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12),
_ended: false,
_timeout: undefined,
_timer: Timer { _object: [Circular], _timeout: null },
sql: 'SELECT * FROM tablename',
values: undefined,
typeCast: true,
nestTables: false,
_resultSet: null,
_results: [],
_fields: [],
_index: 0,
_loadError: null,
_connection:
Connection {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
config:
ConnectionConfig {
host: 'localhost',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'user',
password: 'password',
database: 'database',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
localInfile: true,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
_socket:
Socket {
connecting: true,
_hadError: false,
_handle: [TCP],
_parent: null,
_host: 'localhost',
_readableState: [ReadableState],
readable: false,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
timeout: 10000,
[Symbol(asyncId)]: 5,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]:
Timeout {
_called: false,
_idleTimeout: 10000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 723,
_onTimeout: [Function: bound ],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(unrefed)]: true,
[Symbol(asyncId)]: 9,
[Symbol(triggerId)]: 1 },
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0 },
_protocol:
Protocol {
_events: [Object],
_eventsCount: 7,
_maxListeners: undefined,
readable: true,
writable: true,
_config: [ConnectionConfig],
_connection: [Circular],
_callback: null,
_fatalError: null,
_quitSequence: [Quit],
_handshake: true,
_handshaked: false,
_ended: false,
_destroyed: false,
_queue: [Array],
_handshakeInitializationPacket: null,
_parser: [Parser] },
_connectCalled: true,
state: 'disconnected',
threadId: null } }
Даже здесь ничего мне не помогло
Ответы (1 шт):
Автор решения: Александр Рогонов
→ Ссылка
const mysql = require('mysql');
const connection = mysql.createConnection({
host: "host",
user: "user",
database: "database",
password: "password",
});
connection.connect();
const select__sql = (sql) => new Promise((resolve) => {
connection.query((sql, result) => {
resolve(result);
});
});
const getData = async () => {
console.log(await select__sql('SELECT * FROM tablename'));
};
getData();
Вот так, по простому если. Ну проверки на ошибки нужны и прочие прелести.