幾年前,我做了這樣的事情;該數據庫是關於學術關係/信息,我用prolog和ODBC(加上gui的xpce)。
第一i-打開到數據庫的連接:
fconn(C):-
odbc_connect('academia_info', C, [user(academia_info_user),
password(secret), alias(academia_info), open(once)]).
開放(一次)用於避免重新連接到db和C是一個處理程序
然後我用這個謂詞來提交查詢:
%run_statement(+SQL,-Row)
rs(SQL, Row):-
fconn(Connection),
odbc_query(Connection, SQL, Row).
,如果我想所有的解決方案,我這樣做
%returns all solutions (findall)
%rsall(+SQL,-Rows)
rsall(SQL, Rows):-
findall(Row,rs(SQL,Row), Rows).
例如:
rsall('SELECT * FROM institution', D).
這個謂詞準備的SQL查詢:
prep(SQL, Type, Row,Values):-
fconn(Connection),
odbc_prepare(Connection, SQL, Types,Q), %uses the types of the parameters to prepare Q
odbc_execute(Q,Values,Row). %executes Q by replacing the parameters with their values
例如:
prep('UPDATE professor SET title = ? WHERE id IN (SELECT professor.id FROM professor, researcher, "hadPosition" WHERE professor.id = researcher.id AND professor.id = "hadPosition".researcher_id AND hadPosition.title = ? AND professor.title=? GROUP BY professor.id HAVING sum("hadPosition".end_date - "hadPosition".start_date) > ?*365)',
[varchar,varchar,varchar, integer],_, [MT, LT,LT, Y]).
其中s是由值替換[MT,LT, LT,Y]
這裏我刪除了一些東西
delete(ID,Table):-
swritef(S,'DELETE FROM %t WHERE id = ?', [Table]),
prep(S, [integer], _ , [ID]).
準備語句插入新的值(它以後執行):
prep('INSERT INTO professor (id, title) VALUES (?,?)', [integer, varchar], _, [ID,T]).
BTW odbc_query返回一個值以下格式行(D1,D2,D3,...,DN ) 所以也許你將不得不把它轉換成一個列表。
我希望上面的例子可以幫助..雖然我已經有點忘記了細節:/ 無論如何,整個工程可以發現here但代碼也不是那麼可讀