Swift后台swift.orgSwift后台之路

swift 3.0+perfect+MYSQL搭建服务器

2016-11-12  本文已影响1396人  段帅帅

准备工作

1 安装xcode8.1(8.0有坑)

2 安装homebrew 终端命令行

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

3 安装mysql (一定看清楚mysql安装路径)

brew install mysql

4 我用到的其他辅助工具

1 搭建本地servers

1 clone例子工程PerfectlySoft到本地

git clone https://github.com/PerfectlySoft/PerfectTemplate.git

2 找到例子工程文件夹 打开里面的Package.swift文件 将代码改成下面这样

import PackageDescription

let package = Package(
name: "PerfectTemplate",
targets: [],
dependencies: [
    .Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", majorVersion: 2, minor: 0),
    .Package(url:"https://github.com/PerfectlySoft/Perfect-MySQL.git", majorVersion: 2, minor: 0)
])     

3 cd 到 PerfectTemplate文件夹里 执行
swift package generate-xcodeproj
4 打开PerfectTemplate,发现熟悉的xcodeproj,用xocde打开,编译 然后报错
5 解决方法

错误一
Header '/usr/local/include/mysql/mysql.h'
这个错误是因为我们存放mysql.h文件的路径和它引用的路径不同。用Homebrew安装的MySQL路径确实是正确的。
解决方法:
点击Finder,选择前往文件夹,进入/usr/local目录下,你会发现有mysql文件夹,在文件夹里找到对应mysql.h得到目录,将报错的module.modulemap文件中的路径修改成你自己的路径就可以了。这里我自己最后的路径是/usr/local/mysql-5.7.15-osx10.11-x86_64/include/mysql.h

错误二

ld: library not found for -lmysqlclient for architecture x86_64

解决方法:
在Target中找到MySQL,找到Library Search Paths中加上mysql文件夹下的lib的文件夹路径。我的是/usr/local/Cellar/mysql/5.7.16/lib
在Target中找到PerfectTemplate找到Other Linker Flags 加上-L/usr/local/Cellar/mysql/5.7.16/lib其中在lib目录下能找到对应的mysqlclient文件。

如果还出现错误,赶紧换xcode8.1

6 编译通过 运行打印出
[INFO] Starting HTTP server on 0.0.0.0:8181 with document root ./webroot 然后打开浏览器访问localhost:8181 看到hello word 本地服务器搭建成功

2 启用本地数据库

1 启动数据库
打开XAMPP 选择第一个MYSQL Database 点击start
2 使用sequel 连接数据库,插入表格数据(建表,插入数据一共就几个按钮,自己根据常识点点就会了)
连接数据库所需信息

Host = "127.0.0.1" 
User = "root"//密码默认为空

3 本地服务器与数据库对接

    import PerfectLib
    import PerfectHTTP
    import MySQL


    let testHost = "127.0.0.1"
    let testUser = "admin"
    password is before running these tests
    let testPassword = "duan123"
    let testSchema = "test_db"

    class DBBaseManager {
    func inserData(_ request: HTTPRequest, response: HTTPResponse) -> Void {
    
    // 创建一个MySQL连接实例
     let dataMysql = MySQL() 
    
    let connected = dataMysql.connect(host: testHost, user: testUser, password: testPassword, db: testSchema)
    
    guard connected else {
        // 验证一下连接是否成功
        print(dataMysql.errorMessage())
        return
    }
    
    defer {
        dataMysql.close() //这个延后操作能够保证在程序结束时无论什么结果都会自动关闭数据库连接
    }
    
    //1 创建表格
    let querySuccess_create = dataMysql.query(statement: "CREATE TABLE foo (bar INT(4), baz VARCHAR(16))")
     guard querySuccess_create
        else{
          return
            }  

     //2插入数据
    let str = "duanshuai"
    let querySuccess_insert = dataMysql.query(statement: "INSERT INTO foo VALUES (\(5), '\(str)')")
    
    guard querySuccess_insert
        else{
           //处理插入失败 
           
            return
    }
    try? response.setBody(string: "插入成功")

    
    complate()
    
    }

*main.swift 中

import PerfectHTTPServer
import PerfectLib
import PerfectHTTP
import MySQL


// Create HTTP server.
let server = HTTPServer()

// Register your own routes and handlers
var routes = Routes()
routes.add(method: .post, uri: "/duan", handler: {
request, response in
let dbbase = DBBaseManager()

dbbase.inserData(request, response: response)

//        response.setHeader(.contentType, value: "text/html")
//        response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
//        response.completed()
}
)

// Add the routes to the server.
server.addRoutes(routes)

// Set a listen port of 8181
server.serverPort = 8181

// Set a document root.
// This is optional. If you do not want to serve static content then do not set this.
// Setting the document root will automatically add a static file handler for the route /**
server.documentRoot = "./webroot"

// Gather command line options and further configure the server.
// Run the server with --help to see the list of supported arguments.
// Command line arguments will supplant any of the values set above.
configureServer(server)

do {
// Launch the HTTP server.
try server.start()
} catch PerfectError.networkError(let err, let msg) {
print("Network error thrown: \(err) \(msg)")
}

附一:mysql语句

1 创建表格

     let querySuccess_create = dataMysql.query(statement: "CREATE TABLE foo (bar INT(4), baz VARCHAR(16))")
     guard querySuccess_create
        else{
            resp.code = 1
            resp.codeStatus = "建表失败"  
            complate()
            return
            }  

2 插入数据

    let str = "woshi"
    let querySuccess_create = dataMysql.query(statement: "INSERT INTO foo VALUES (\(5), '\(str)')")
    guard querySuccess_create
        else{
            resp.code = 1
            resp.codeStatus = "插入失败"  
            complate()
            return
    }

3 查询数据

    let querySuccess = dataMysql.query(statement: "SELECT count FROM DS_USER") 
    guard querySuccess  else {
        resp.codeStatus = "选取count字段失败"
        resp.code = 1;
        complate()
        return
    }

附二:参考文档

最后:我是一名ios开发者,欢迎加我q576616412交流技术,互相学习。

swift学习交流群

IMG_0835.JPG
上一篇下一篇

猜你喜欢

热点阅读