## orm 数据库连接模块,支持mysql,sqlite,postgress,mssql(已关闭此数据库支持,有需要的伙伴可以反馈),oracle(不支持,有需要的伙伴可以反馈) ## 方法介绍: | orm方法名称 | 作用 | | --- | --- | | exec | 执行sql | | query | 查询sql | | open | 链接数据库 | | close | 关闭数据库 | |set_timeout|设置超时(暂时无效)| ## 1.myql数据库操作 >**注意:**想要正确的处理`time.Time`,您需要带上`parseTime`参数, 要支持完整的 UTF-8 编码,您需要将`charset=utf8`更改为`charset=utf8mb4`查看[此文章](https://mathiasbynens.be/notes/mysql-utf8mb4)获取详情 ~~~woo local c = woo.orm:new() local sql='select * from member' local database_adapter='mysql' local database='wooyri' local conn_str='root:123@(127.0.0.1:3306)/'..databbase..'?charset=utf8&parseTime=True&loc=Local' local ok, err = c:open(database_adapter, conn_str) if ok then c:query(sql, function(res_) print(_json_encode(res)) end) c:close() else print(err) end ~~~ ## 2.sqlite3 数据库操作,支持密码加密 ~~~woo -- 窗口表sql local create_sql = [[ CREATE TABLE if not exists foo ( "id" INTEGER primary key AUTOINCREMENT, "name" TEXT, "created_at" INTEGER, "updated_at" INTEGER ); ]] -- 实例化一个orm句柄 local c = woo.orm:new() -- 数据库用户名 local user='oshine' -- 数据库密码,由于有特殊字符串,需要url编码下 local psw = _url_encode('nihfhuiaye87125636$%^&^^%#2515') local ok, err = c:open('sqlite3', ('file:tttt.woo3db?_auth&_auth_user=%s&_auth_pass=%s&_auth_crypt=sha256'):format(user,psw)) _out('res:', err) print("ok") res, err = c:exec(create_sql) _out(res, err) res, err = c:exec("insert into foo( name, created_at) values( '小明:" .. _rand(_time()) .. "','" .. _time() .. "')") _out(res, err) print('') c:query("select id, name,created_at from foo", function(res_) --print(_json_encode(res_)) res_.created_at = _date('Y-m-d H:i:s', res_.created_at) _out('\n', res_) end) c:close() ~~~ ## 3. PostgreSQL ~~~woo local c = woo.orm:new() sqlStmt = [[ create table if not exists "foo" ( id serial not null constraint foo_pk primary key, name varchar(100) ); alter table "foo" owner to postgres; create unique index foo_id_uindex on "foo" (id); ]] local database_adapter = 'postgres' local conn_str = "user=postgres password=oshine dbname=database_name sslmode=disable" local ok, err = c:open(database_adapter, conn_str) if ok then local r1 = c:exec(sqlStmt) print(r1) local r, err = c:exec("insert into foo(id, name) values(1, 'nihao')") print('取影响行数',r, err) local r, err = c:exec("insert into foo(id, name) values(100, 'nihao')",true) print('取最后插入的id',r, err) c:query("select id, name from foo", function(res_) print(_json_encode(res_)) end) c:close() else print(err) end ~~~ 输出: >0 取影响行数 1 nil 取最后插入的id 0 nil {"id":1,"name":"nihao"} {"id":100,"name":"nihao"}