mysqljs / sqlstring

Simple SQL escape and format for MySQL
MIT License
403 stars 78 forks source link

can it support set alias? #62

Closed fashen007 closed 3 years ago

fashen007 commented 3 years ago

for example

var userId = 1;
var columns = ['username AS 用户名', 'email AS 邮箱'];
var sql     = SqlString.format('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId]);

How to make this work correctly?

dougwilson commented 3 years ago

You would use the toSqlString functionality to create column objects. There are many ways to do this, but here is one:

function Column(name, alias) {
  return SqlString.raw(SqlString.format('?? AS ??', [name, (alias || name)]))
}
var userId = 1;
var columns = [Column('username', '用户名'), Column('email', '邮箱')];
var sql     = SqlString.format('SELECT ? FROM ?? WHERE id = ?', [columns, 'users', userId]);