參考自d程序設計語言---個人博客http://my.oschina.net/u/218155/blog?fromerr=SwOkb7Sw fllow memysql
d操做mysqlsql
d有個很方便的工具dub,他須要編寫格式化的json文件數據庫
dub說明見 http://code.dlang.org/package-format?lang=json json
個人dub格式,保存爲dub.jsonapp
{ "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便可spa
具體代碼.net
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; }