連線資料庫

2021-10-03 20:49:58 字數 2867 閱讀 9466

連線資料庫我們需要使用到ngx_lua的第三方庫:

這兩個庫都是基於cosocket實現的,特點是非同步非阻塞。**風格是同步的寫法。更多第三方庫詳見:see also 。

example拷貝官網:

server 

local ok, err, errcode, sqlstate = db:connect

if not ok then

ngx.say("failed to connect: ", err, ": ", errcode, " ", sqlstate)

return

endngx.say("connected to mysql.")

local res, err, errcode, sqlstate =

db:query("drop table if exists cats")

if not res then

ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")

return

endres, err, errcode, sqlstate =

db:query("create table cats "

.. "(id serial primary key, "

.. "name varchar(5))")

if not res then

ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")

return

endngx.say("table cats created.")

res, err, errcode, sqlstate =

db:query("insert into cats (name) "

.. "values (\'bob\'),(\'\'),(null)")

if not res then

ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")

return

endngx.say(res.affected_rows, " rows inserted into table cats ",

"(last insert id: ", res.insert_id, ")")

-- run a select query, expected about 10 rows in

-- the result set:

res, err, errcode, sqlstate =

db:query("select * from cats order by id asc", 10)

if not res then

ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")

return

endlocal cjson = require "cjson"

ngx.say("result: ", cjson.encode(res))

-- put it into the connection pool of size 100,

-- with 10 seconds max idle timeout

local ok, err = db:set_keepalive(10000, 100)

if not ok then

ngx.say("failed to set keepalive: ", err)

return

end-- or just close the connection right away:

-- local ok, err = db:close()

-- if not ok then

-- ngx.say("failed to close: ", err)

-- return

-- end';}

}

example拷貝官網:

server }}

1.啟動redis

redis-5.0.8/src/redis-server
2.請求nginx

curl http://localhost:8080/test
3.查詢redis確認資料是否寫入成功

參考:redis 介面的二次封裝(簡化建連、拆連等細節) · openresty最佳實踐

增加檔案conf/lua/red.lua

local redis = require "resty.redis_iresty"

local red = redis:new()

local ok, err = red:set("dog", "an animal")

if not ok then

ngx.say("failed to set dog: ", err)

return

endngx.say("set result: ", ok)

修改nginx.conf

location /red
請求nginx

連線資料庫

2 documents 目錄就是我們可以用來寫入並儲存檔案得地方,一般可通過 nsarray paths nssearchpathfordirectoriesindomains nsdocumentdirectory,nsuserdomainmask,yes nsstring documentsdi...

連線資料庫

1 oracle8 8i 9i資料庫 thin模式 class.forname oracle.jdbc.driver.oracledriver newinstance string url jdbc oracle thin localhost 1521 orcl orcl為資料庫的sid strin...

連線資料庫

public void connection 以上是連線資料庫的乙個方法,以及從資料庫中取到資料後存放在table中.executenonquery 執行sql後,返回乙個整形變數,如果sql是對資料庫記錄進行操作,那麼返回影響的記錄條數。executescalar 執行sql 如果sql語句是se...