mysql lang_dlang操作mysql

本文介绍如何利用D语言的dub工具和mysql-native库来连接及操作MySQL数据库,包括增删改查的基本操作。首先,配置dub.json文件添加依赖vibe-d和mysql-native。接着,创建source目录并编写app.d脚本,实现数据的插入、更新、删除和查询功能。通过lockConnection确保连接池的安全,并在退出时关闭连接。
摘要由CSDN通过智能技术生成

d操作mysql

d有个很方便的工具dub,他需要编写格式化的json文件

dub说明见 http://code.dlang.org/package-format?lang=json

我的dub格式,保存为dub.json{

"name": "testmysql",

"description": "test mysql connect.",

"authors": ["cabing_2005@126.com"],

"homepage": "http://my.oschina.net/u/218155/blog?catalog=3451757",

"license": "GPL-2.0",

"dependencies": {

"vibe-d": "~>0.7.17",

"mysql-native" :"~>0.1.3",

}

}

我使用了vibe.d的连接池和mysqlnative的数据库包所以把他们都放进依赖里。

文件结构在当前目录下新建一个目录命名为source 在source下新建一个脚本app.d

最后运行代码 在source的上一级运行 dub即可

具体代码import mysql.common;

import mysql.connection;

import mysql.result;

import mysql.db;

import std.stdio;ulong testExce(Connection cn,string sql){auto cmd = Command(cn);

cmd.sql = sql;

ulong rowsAffected;

cmd.execSQL(rowsAffected);

return rowsAffected;

}ResultSet testRows()(Connection cn, string sql){

auto cmd = Command(cn);

cmd.sql = sql;

return cmd.execSQLResult();

}void testMysql(){

string connStr = "host=localhost;port=3306;user=root;pwd=123456;db=test";

auto mdb = new MysqlDB(connStr);

auto con = mdb.lockConnection();

scope(exit) con.close();

//测试增删改查 //add auto addSql = "insert into country(name,user_age,id)values('helloworld',59,1)";

writeln("add data is ", testExce(con,addSql));

//update auto updateSql = "update country set name = 'helloworld' where id=1 limit 1";

writeln("update data is ", testExce(con,updateSql));

//delte auto delSql = "delete from country where id=1 limit 1";

writeln("delete data is ", testExce(con,delSql));

//select auto selSql = "select name,user_age,id from country";

ResultSet rs = testRows(con,selSql);

int i;

auto keys = ["name","user_age","id"];

for(i=0;i

foreach(k,v;keys){

writef("%s:%s",v,rs[i][k]);

}

writeln("");

}

writeln(rs[0],rs[0][0],rs[0][1]);

}int main(char[][] args) {

testMysql();return 0;

}

f68f2add0b68e4f9810432fce46917b7.png

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值