2
votes

Is there a way to retrieve data from MySQL to Prolog knowledge base?

I am trying to retrieve, for example, the fields: Name and price from a table chair in a MySQL database to a Prolog knowledge base rather than declaring them in Prolog.

1
It's important to know which Prolog you're using, because different DB interfaces are available, with varying degree of sophistication. - CapelliC
See the comment by @CapelliC. And if nothing else is available, you can always use streams to send a query to the database and read the answer. - user1812457
Iam using JiProlog - amy

1 Answers

3
votes

The comment by @Boris is interesting. Assuming available a builtin that issues a shell command and get the output stream (in SWI-Prolog we can use library(process)), here is a simple interface to query a Wordpress table from MySQL

query(USER, PWD, DB, QUERY, Columns, Rows) :-
    atom_concat('-p', PWD, PPWD),
    process_create(path(mysql), ['-u', USER, PPWD, '-D', DB, '-e', QUERY], [stdout(pipe(Out)),stderr(std)]),
    read_record(Out, Columns),
    read_records(Out, Rows).

read_record(Out, Fields) :-
    read_line_to_codes(Out, Codes),
    Codes \= end_of_file,
    atom_codes(Line, Codes),
    atomic_list_concat(Fields, '\t', Line).

read_records(Out, [Record|Rs]) :-
    read_record(Out, Record),
    !, read_records(Out, Rs).
read_records(Out, []) :-
    close(Out).

test run:

test_query :-
    query('------','-----',a_blog,"select * from wp_options limit 10", Cols,Rows),
    writeln(columns:Cols),
    maplist(writeln, Rows).

yields

?- test_query.
columns:[option_id,option_name,option_value,autoload]
[1,siteurl,http://localhost/a_blog,yes]
[2,home,http://localhost/a_blog,yes]
[3,blogname,a blog,yes]
[4,blogdescription,Just another WordPress site,yes]
[5,users_can_register,0,yes]
...
true.

so, instead of display, just assert the records:

capture_table(USER, PWD, DB, QUERY, Functor) :-
    query(USER, PWD, DB, QUERY, _Columns, Rows),
    maplist(capture_table(Functor), Rows).
capture_table(Functor, Row) :-
    Clause =.. [Functor|Row],
    assertz(Clause).