跳转到内容


dlang 使用 ddbc 操作查询数据库

dlang ddbc

  • 您无法回复此主题
No replies to this topic

#1 冰力

    Administrator

  • 总版主
  • 1260 帖子数:

发表于 2016/12/25 22:10:25

首先使用sqlite创建一个用户表
CREATE TABLE "test_user" ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `email` TEXT, `role_id` INTEGER, `status` BLOB DEFAULT 1 )

然后安装数据库编译用的静态依赖包(我的开发环境是debian9)
apt install libpq-dev libsqlite3-dev libmysqlclient-dev

我们写一个例子试试看
import ddbc.all;

import std.stdio;

struct User
{
    int id;
    string name;
    string email;
    int role_id;
    bool status;
}

struct Role
{
    int id;
    string role;
}

void main()
{
    // TODO
    string url = "sqlite:database/test.db";
    auto conn = createConnection(url);
    scope(exit) conn.close();

    Statement stmt = conn.createStatement();
    scope(exit) stmt.close();

    // INSERT DATA
    stmt.executeUpdate("INSERT INTO test_user (name, email, role_id, status) VALUES ('zoujiaqing', 'zoujiaqing@test.com', 3, 1), ('Brian Zou', 'brian@test.com', 1, 1)");

    auto rs = stmt.executeQuery("SELECT id, name, email, role_id, status FROM test_user");
    while(rs.next())
    {
	    writeln(rs.getString(2));
    }
}

看一下结果吧

zoujiaqing@debian:~/Projects/next-entity$ dub run -v
Running ./test 
zoujiaqing
Brian Zou