![](/img/trans.png)
[英]What is the JavaScript equivalent of MySQL's %LIKE% clause?
[英]Postgres equivalent of MySQL's SET?
我正在嘗試從MySQL遷移到Postgres,但遇到了一些問題。 我有一個表單,其中用戶填寫了大約40個字段,並將這些值插入到數據庫中。 使用MySQL,我習慣這樣做:
INSERT INTO table_name SET name="John Smith", email="jsmith@gmail.com", website="jsmith.org";
我還在nodejs中使用mysql
模塊,這是我的代碼當前的樣子:
var data = {
name: req.body.name,
email: req.body.email,
website: req.body.website,
...
...
}
var query = connection.query('INSERT INTO table_name SET ?', data)
由於SET
不是有效的SQL,如果我想使用Postgres,則使用pg
模塊的查詢如下所示:
client.query('INSERT INTO table_name (name, email, website) VALUES ($1, $2, $3)', req.body.name, req.body.email, req.body.website)
考慮到我有近40個領域,這將非常繁瑣。
有什么更好的方法可以做到這一點,還是我不得不手動編寫查詢?
謝謝。
由於您已經有一個包含相關數據的對象
var data = {
name: req.body.name,
email: req.body.email,
website: req.body.website,
...
...
}
您可以編寫一個查詢函數,該函數包裝pg
客戶端的query
方法並添加對對象即值的支持:
function insert(client, table, values) {
const keys = Object.keys(values),
// IMPORTANT: escape column identifiers. If `values` should come
// from an uncontrolled source, naive concatenation would allow
// SQL injection.
columns = keys.map(k => client.escapeIdentifier(k)).join(', '),
placeholders = keys.map((k, i) => '$' + (i + 1)).join(', ');
return client.query(`INSERT INTO ${client.escapeIdentifier(table)}
(${columns}) VALUES (${placeholders})`,
// According to docs `query` accepts an array of
// values, not values as positional arguments.
// If this is not true for your version, use the
// spread syntax (...args) to apply values.
keys.map(k => values[k]));
}
...
insert(client, 'table_name', data);
另外,您可能可以使用sql-template-strings
重寫查詢,這似乎很不錯。
當使用pg-promise時 ,這很容易實現,這是完整的代碼:
var pgp = require('pg-promise')();
var db = pgp(/*connection details*/);
app.get('/get', (req, res)=> {
var insert = pgp.helpers.insert(req.body, null, {table: 'table_name'});
db.none(insert)
.then(()=> {
// success
})
.catch(error=> {
// error
});
});
API: helpers.insert , 無
方法helpers.insert可以為您生成完整的INSERT
語句,格式正確。
這不僅是最簡單的方法,而且也是最靈活的方法,因為您無需進行任何更改即可開始生成多插入語句,即,如果insert
方法的第一個參數是對象數組,您將獲得您的多插入查詢。
而且,如果您只需要請求中的特定屬性,那么最好的方法是將它們分別指定為請求之外的ColumnSet (為了可重復使用,以實現最佳性能):
var cs = new pgp.helpers.ColumnSet(['name', 'email', 'website'], {table: 'table_name'});
app.get('/get', (req, res)=> {
var insert = pgp.helpers.insert(req.body, cs);
db.none(insert)
.then(()=> {
// success
})
.catch(error=> {
// error
});
});
沒有轉換
app.get('/get', (req, res)=> {
var insert = pgp.helpers.insert(req.body, cs) + 'RETURNING id';
db.many(insert)
.then(data=> {
// success
})
.catch(error=> {
// error
});
});
轉換后
app.get('/get', (req, res)=> {
var insert = pgp.helpers.insert(req.body, cs) + 'RETURNING id';
db.map(insert, [], a=>a.id)
.then(ids=> {
// ids = array of id-s
})
.catch(error=> {
// error
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.