作者:u014388424----感谢原创,感谢作者!!
标签:swift 服务器端 project 模版 connector
<pre code_snippet_id="1576144" snippet_file_name="blog_20160208_1_4535071" name="code" class="plain">
import PerfectLib
import MySQL
let HOST = "你的数据库链接"
let USER = "你的帐号"
let PASSWORD = "你的密码"
let SCHEME = "你的数据库"
public func PerfectServerModuleInit() {
Routing.Handler.registerGlobally()
Routing.Routes["GET", ["/"]] = { (_:WebResponse) in return PerfectHandler() }
print("\(Routing.Routes.description)")
}
//Create a handler for index Route
class PerfectHandler: RequestHandler {
func handleRequest(request: WebRequest, response: WebResponse) {
response.addHeader("Content-Type", value: "application/json")
response.addHeader("Content-Type", value: "text/html; charset=utf-8")
let mysql = MySQL()
let connect = mysql.connect(HOST, user: USER, password: PASSWORD)
if(connect)
{
let sres = mysql.selectDatabase(SCHEME)
if(sres)
{
let sres2 = mysql.query("SELECT name,memo FROM Info")
if(sres2)
{
let results = mysql.storeResults()!
if(results.numRows()==0)
{
do{
let encoder = JSONEncoder()
let data = try encoder.encode(["result": ""])
response.appendBodyString(data)
}
catch{
response.setStatus(500, message: "Could not create data")
}
}
else
{
var dataArray:Array<AnyObject> = []
var dict = Dictionary<String,String>()
while let row = results.next() {
dict["name"]=row[0];
dataArray.append(dict)
}
print(NSJSONSerialization.isValidJSONObject(dataArray))
do {
let dataFinal = try NSJSONSerialization.dataWithJSONObject(dataArray, options:NSJSONWritingOptions(rawValue:0))
let string = NSString(data: dataFinal, encoding: NSUTF8StringEncoding)
let tee : String = string as! String
response.appendBodyString(tee)
}
catch{
response.setStatus(500, message: "Could not create data")
}
}
results.close()
}
}
mysql.close()
}
response.requestCompletedCallback()
}
}
</pre>
|