Advanced-Database
Z1h has embedded database operations, the main ones include mysql
andsqlite3
If you need to support Postgres
/ Tidb
/ MsSql
/ Oracle
, please contact the author
Open
Refer to Run Configuration, and configure the db
information, you can connect to the database
...
{
"db": {
"type": "mysql", // database type
"address": "" // database connection address, sqlite3 writable filename
}
}
...
there are two ways to perform database operations:SQL
way and ORM
way
SQL operation
by$ db
can operate SQL
// Create table
assert ($ db (` CREATE TABLE test_db (name VARCHAR) `))
// Insert
assert ($ db (` INSERT INTO test_db (name) VALUES ("aaa") `))
// placeholder
assert ($ db (` INSERT INTO test_db (name) VALUES (?) `,"bbb"))
// delete
assert ($ db (`DELETE FROM test_db WHERE name =?`, "aaa"))
// query
assert ($ db (`SELECT * FROM test_db WHERE name! =?`, "aaa"))
// modify
assert ( $ db (`UPDATE test_db SET name =? WHERE name! =?`, "aaa", "aaa"))
// ...
// For more operations, please learn SQL
ORM
object relational mapping (Object Relational Mapping (ORM for short) is to automatically persist objects in an object-oriented language program into a relational database by using metadata describing the mapping between objects and databases.
go-xorm
If you are using the Go version of Z1h, built environment https://github.com/go-xorm/xorm third-party libraries
by $ xorm
can be operated in a database ORM
// Build table
var table_struct = new ('struct', {
id: 0,
username:` `,
password:` `,
age: 0,
updateAt: now (),
createAt: now(),
}, {
id: `xorm:"not null pk autoincr INT(11)"`,
username: `xorm:"not null VARCHAR(64) unique(openid)"`,
password: `xorm:"not null VARCHAR(64)"`,
age: `xorm:"not null int(11) default 18"`,
updateAt: `xorm:"updated"`,
createAt: `xorm:"created"`,
});
assert($xorm.Table('test_db2').Sync2(table_struct))
// Insert
assert($xorm.Table('test_db2').Insert({
username: 'admin',
password: md5("Password").hex(),
age: 12,
}))
// Insert with datetime
assert($xorm.Table('test_db2').Insert(new(table_struct, {
username: 'admin2',
password: md5("Password2").hex(),
age: 12,
})))
// Delete
assert($xorm.Table('test_db2').Id(1).Delete(new(table_struct)))
assert($xorm.Table('test_db2').Where('username = ?', 'admin').Delete(new(table_struct)))
// Query
var results = &new(table_struct, '[]');
assert($xorm.Table('test_db2').Where('username = ?', 'admin1').Find(results));
results = *results;
print(results.map(e=>{e.username}).join(' and '));
// Update
assert($xorm.Table('test_db2').Id(2).Update(new(table_struct, {
username: 'hello',
})))
// ...
// More infomation via https://github.com/go-xorm/xorm