2016-04-06 30 views
-3
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). 

assertz(Clause). 
+0

这显然是为MySQL编写的数据库。你的数据库是MySQL吗?看起来很清楚,“USER”是你的db用户名,“PWD”是用户的密码,“DB”是数据库名,“QUERY”是你想要执行的查询。你还需要知道为了尝试它吗?这个声明“assertz(Clause).'本身,在这里的任何其他语境是没有意义的。 – lurker

+0

在哪里放表的名称和列的名称? – AAAA

+0

它全部内置到查询字符串中。这里的“QUERY”是一个MySQL查询。这就是你展示的代码的结构。 – lurker

回答

1

你没有太多道理。通过应用数据库,我假设你有一系列基础事实,并且你希望这个谓词集可以与它一起运行。

如果是这样,您需要阅读关于序言的统一。

1

正如我在我的评论描述,它似乎很清楚,USER是你的数据库的用户名,PWD是用户的密码,DB是数据库名,QUERY是要执行查询。 QUERY是您要执行的完整MySQL查询字符串。有关查询的所有信息(包括哪些表,哪些字段和条件)都包含在该查询字符串中。这是一个标准的MySQL查询字符串。据了解,您提供的用户名和密码有适当的权限来执行您将在QUERY中提供的查询。

例如,假设您有一个名为mydb的MySQL数据库。也 假设mydb有一个表叫mytable看起来像这样:

id foo bar 
-- --- --- 
1 ick poo 
2 oh  yeah 

并进一步假设你的MySQL数据库mydb是通俗易懂的用户fred与密码,freds=password。然后你就可以用你表示Prolog的代码下面的查询:

?- query('fred', 'freds=password', 'mydb', 'select * from mytable', Cols, Rows). 

这将产生:

Cols = ['id', 'foo', 'bar'] 
Rows = [['1', 'ick', 'poo'], ['2', 'oh', 'yeah']] 

或者,你可以这样做:

?- query('fred', 'freds=password', 'mydb', 'select id, bar from mytable limit 1', Cols, Rows). 

这将产生:

Cols = ['id', 'bar'] 
Rows = [['1', 'poo']] 
相关问题