dlang操作mysql
程序员文章站
2022-03-10 13:55:13
...
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<rs.length;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; }
下一篇: 一个简单爬虫的开发