I am new to Jena and SPAQL , trying to run jena in eclipse with below code , getting Query Parse Exception. This Query is executing fine on http://dbpedia.org/sparql
What I want is Birth Place
Exception
com.hp.hpl.jena.query.QueryParseException: Line 1, column 84: Unresolved prefixed name: dbpedia-owl:birthPlace
Query
PREFIX res: <http://dbpedia.org/resource/>
SELECT DISTINCT ?string
WHERE {
res:David_Cameron dbpedia-owl:birthPlace ?string .
}
Java Code
import org.apache.jena.atlas.logging.Log;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.sparql.engine.http.QueryExceptionHTTP;
public class GetDateOfBirth {
private String service = null;
public GetDateOfBirth(String service)
{
this.service = service;
}
public void TestConnection(){
QueryExecution qe = QueryExecutionFactory.sparqlService(service, "ASK {}");
try{
if(qe.execAsk())
{
System.out.println(service + " is UP");
}
}catch(QueryExceptionHTTP e){
e.printStackTrace();
System.out.println(service + "is Down");
}
finally {
qe.close();
}
}
public ResultSet executeQuery(String queryString) throws Exception {
QueryExecution qe = QueryExecutionFactory.sparqlService(service, queryString);
return qe.execSelect();
}
public static void main(String[] args) {
Log.setCmdLogging() ;
String sparqlService = "http://dbpedia.org/sparql";
/*
* More query examples here:
* http://sparql.bioontology.org/examples
*/
String query = "PREFIX res: <http://dbpedia.org/resource/>" +
" SELECT ?dob WHERE { res:David_Cameron dbpedia-owl:birthPlace ?string .}";
try {
GetDateOfBirth con= new GetDateOfBirth(sparqlService);
ResultSet results = con.executeQuery(query);
for ( ; results.hasNext() ; ) {
QuerySolution soln = results.nextSolution() ;
System.out.println(soln.getResource("?dob").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Just like you define the prefix PREFIX res: <http://dbpedia.org/resource/>, you need to specify a prefix for dbpedia-owl. Using DBPedia's Predefined Namespace Prefixes, I assume the updated query would look like this:
PREFIX res: <http://dbpedia.org/resource/>
PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>
SELECT DISTINCT ?string
WHERE {
res:David_Cameron dbpedia-owl:birthPlace ?string .
}
Related
spring Boot project gives me No message available, null output! i know this error means i have an issue with my code but i am so new to the ontologies and TDB so please help! I am trying to bring all the individualsfrom my rdf file and store it in TDB and i can't find helpful answer!
Example.java
public class Example {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
ExampleController.java
#RestController
public class ExampleController {
File file;
Model model;
InfModel infModel;
Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
Dataset dataset;
QueryExecution qe;
#RequestMapping("/getAll")
public List getAllIndiv() {
List list = new ArrayList();
try {
String directory = "tdb" ;
dataset = TDBFactory.createDataset(directory) ;
dataset.begin(ReadWrite.READ) ;
String uri ="http://example#";
model = dataset.getNamedModel(uri);
String source = "example.owl";
FileManager.get().readModel(model, source);
String a = "";
String queryString = "\r\n"
+ "PREFIX ns: <http://example#>"
+ "PREFIX rdf: <http://example-syntax-ns#>" + "SELECT ?Individuals " + "WHERE {"
+ "?Individuals rdf:type ns:Concept." + "}";
Query query = QueryFactory.create(queryString);
query.getQueryPattern();
qe = QueryExecutionFactory.create(query, dataset);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(results);
while (results.hasNext()) {
QuerySolution result = (results.next());
RDFNode ind = result.get("Individuals");
a = ind.asResource().getLocalName() + "";
list.add(a);
qe.close();
}
return list;
} catch (Exception e) {
e.printStackTrace();
}finally {
if(model != null && dataset != null) {
qe.close();
dataset.commit();
model.close();
dataset.end();
}
}
return null;
}
}
I wrote stored procedure in MySQL which looks like this (it works):
DELIMITER //
CREATE PROCEDURE getBrandRows(
IN pBrand VARCHAR(30),
OUT pName VARCHAR(150),
OUT pType VARCHAR(200),
OUT pRetailPrice FLOAT)
BEGIN
SELECT p_name, p_type, p_retailprice INTO pName, pType, pRetailPrice
FROM part
WHERE p_brand LIKE pBrand;
END//
DELIMITER ;
I try to return multiple results and display them. I've tried many ways described here on Stack and in Internet but that does not help me. I have edited my entire code and created a simple one so you can guys paste it and compile. It should work but with error. Here is the code:
package javamysqlstoredprocedures;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class JavaMySqlStoredProcedures {
private final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private final String DB_URL = "jdbc:mysql://anton869.linuxpl.eu:3306/"
+ "anton869_cars?noAccessToProcedureBodies=true";
private final String DB_USER = "xxx";
private final String DB_PASSWORD = "xxx";
class CallStoredProcedureAndSaveXmlFile extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() {
displaySql();
return null;
}
#Override
public void done() {
}
private void displaySql() {
try {
System.out.println("Connecting to MySQL database...");
Class.forName(DEFAULT_DRIVER);
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD)) {
System.out.println("Connected to MySQL database");
CallableStatement cs = conn.prepareCall("{CALL getBrandRows("
+ "?, ?, ?, ?)}");
cs.setString(1, "Brand#13");
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(3, Types.VARCHAR);
cs.registerOutParameter(4, Types.FLOAT);
boolean results = cs.execute();
while (results) {
ResultSet rs = cs.getResultSet();
while (rs.next()) {
System.out.println("p_name=" + rs.getString("p_name"));
System.out.println("p_type=" + rs.getString("p_type"));
System.out.println("p_retailprice=" + rs
.getFloat("p_retailprice"));
}
rs.close();
results = cs.getMoreResults();
}
cs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public JavaMySqlStoredProcedures() {
new CallStoredProcedureAndSaveXmlFile().execute();
}
public static void main(String[] args) {
JavaMySqlStoredProcedures jmssp = new JavaMySqlStoredProcedures();
}
}
ResultSet can handle multiple records.I found some errors in your code.Try these steps
Move your all close method to finally block.
try {
//do something
} catch (Exception e) {
//do something
} finally {
try{
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
//do something
}
}
You can put your result into List. See sample
List<YourObject> list = new ArrayList<YourObject>();
while (rs.next()) {
YourObject obj = new Your Object();
obj.setName(rs.getString("p_name"));
obj.setType(rs.getString("p_type"));
obj.setRetailPrice(rs.getFloat("p_retailprice"));
list.add(obj);
}
Make sure your query is correct and database connection is Ok.
Don't use IN or OUT parameter if you just simply want to display result. And also you should add '%%' in your LIKE clause with the help of CONCAT function. Please try this one:
DELIMITER //
CREATE PROCEDURE getBrandRows(
pBrand VARCHAR(30)
)
BEGIN
SELECT p_name, p_type, p_retailprice INTO pName, pType, pRetailPrice
FROM part
WHERE p_brand LIKE CONCAT("%", pBrand, "%");
END//
DELIMITER ;
I am posting correct solution to everybody who have smiliar problem:
1. Corrected Stored Procedure:
DELIMITER //
CREATE PROCEDURE getBrandRows(
IN pBrand VARCHAR(30))
BEGIN
SELECT p_name, p_type, p_retailprice
FROM part
WHERE p_brand = pBrand;
END//
DELIMITER ;
2. Corrected Java code:
package javamysqlstoredprocedures;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class JavaMySqlStoredProcedures {
private final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private final String DB_URL = "jdbc:mysql://anton869.linuxpl.eu:3306/"
+ "anton869_cars?noAccessToProcedureBodies=true";
private final String DB_USER = "xxx";
private final String DB_PASSWORD = "xxx";
class CallStoredProcedureAndSaveXmlFile extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() {
displaySql();
return null;
}
#Override
public void done() {
}
private void displaySql() {
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
try {
System.out.println("Connecting to MySQL database...");
Class.forName(DEFAULT_DRIVER);
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
System.out.println("Connected to MySQL database");
cs = conn.prepareCall("{CALL getBrandRows(?)}");
cs.setString(1, "Brand#13");
boolean results = cs.execute();
while (results) {
rs = cs.getResultSet();
while (rs.next()) {
System.out.println("p_name=" + rs.getString("p_name"));
System.out.println("p_type=" + rs.getString("p_type"));
System.out.println("p_retailprice=" + rs.getFloat(
"p_retailprice"));
}
results = cs.getMoreResults();
}
} catch (SQLException | ClassNotFoundException e) {
} finally {
try {
if (rs != null ) rs.close();
if (cs != null) cs.close();
if (conn != null) conn.close();
} catch (SQLException e) {
}
}
}
public JavaMySqlStoredProcedures() {
new CallStoredProcedureAndSaveXmlFile().execute();
}
public static void main(String[] args) {
JavaMySqlStoredProcedures jmssp = new JavaMySqlStoredProcedures();
}
}
Your stored procedure returns more than one row. Just correct logic behind your select query inside the stored procedure it should return only one row.
here how to return multiple value
Good night guys.
I'm doing a java applet to handle that uses the database, in times of insertion works right, the problem is in the update and delete the executeUpdate loops.
for example, if I try to insert the following code by java will not. Now the cmd will.
UPDATE CIDADE SET NOME_CIDADE = 'Alegre', UF = 'ES' WHERE CODCIDADE = '4'
My class connection to the database is as follows:
package gbd1.util.conexoes;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConexaoOracle implements IConexoes {
private Connection con;
private String nomeUsuario;
private String senha;
private String database;
private PreparedStatement ps = null;
private Statement stat = null;
#Override
public Connection IniciarConexao(String database, String usuario, String senha) throws SQLException {
this.database = database;
this.nomeUsuario = usuario;
this.senha = senha;
try {
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:XE", "Paula", "2011204415");
stat = con.createStatement();
return con;
} catch (ClassNotFoundException e) {
throw new SQLException(e.getMessage());
}
}
public ResultSet querySelect(String sql) throws SQLException {
ResultSet rs = null;
rs = stat.executeQuery(sql);
return rs;
}
public int updadeBanco(String sql) throws SQLException {
stat = con.createStatement();
int i = stat.executeUpdate(sql);
return i;
}
}
This is the where clase call the executeUpdate..
public class RecuperacaoDados {
private static IConexoes conexao;
public static void recuperar(String sgbd, String nomeBd, String nomeUsuario, String senha) throws Exception{
//conexao = CriarConexao.create(sgbd);
conexao = new ConexaoOracle();
conexao.IniciarConexao("", "", "");
//---------------------------------------
LogsCollection logs = LogsCollection.getLogs(null);
String query;
String atri;
String valu;
int i, j=0;
for (Log l:logs.getLogs()){
query ="";
atri="";
valu="";
j=0;
System.out.println(l.getOperacao());
if(l.getOperacao().equalsIgnoreCase("INSERT")){
query= "INSERT INTO "+ l.getNomeTabela();
i = l.getAtributos().size();
for (Atributo at: l.getAtributos()){
if( (j!=0)){
atri=atri+", ";
valu=valu+", ";
}
atri=atri+at.getNomeAtributo();
valu=valu+"'"+at.getValorAtributo()+"'";
j++;
}
query = query + " ("+ atri + ") VALUES ("+valu+ ")";
System.out.println(query);
conexao.updadeBanco(query);
}
else if(l.getOperacao().equalsIgnoreCase("UPDATE")){
query= "UPDATE "+ l.getNomeTabela()+ " SET " ;
i = l.getAtributos().size();
for (Atributo at: l.getAtributos()){
if( (j!=0)){
query=query+ ", ";
}
query = query+ at.getNomeAtributo()+" = '"+ at.getValorAtributo()+"'";
j++;
}
query = query + " WHERE ";
j=0;
for ( ChavePrimaria at: l.getPks()){
if( (j!=0)){
query=query+ " AND ";
}
query = query+ at.getNome()+" = "+ at.getValor()+"";
// atri=atri+at.getNomeAtributo();
// valu=valu+"'"+at.getValorAtributo()+"'";
j++;
}
// query = query + " ("+ atri + ") VALUES ("+valu+ ")";
query = "DELETE CIDADE WHERE CODCIDADE = 2";
System.out.println(query);
conexao.updadeBanco(query);
}
}
}
}
I put the query as "default" for testing...
Can anyone help me?
update:
I found it was error on the drive.
I am using Jena APIs to insert and update triples in Jena TDB. My design is such that each of the insert operation is within the transaction control. For example:
dataset.begin (ReadWrite.WRITE)
try
{
// 1st insert operation
dataset.commit()
} finally {
dataset.end();
}
dataset.begin (ReadWrite.WRITE)
try
{
// 2nd insert operation
dataset.commit()
} finally {
dataset.end();
}
After this, when I query the TDB using the READ transaction , I notice that some of the entries (either subject, predicate, or object) are empty. Why does it behaves this way, even though I am not using nested transactions?
Insert Code
public class UpdateTDB2 {
String directory = "C://myTDB//";
Dataset dataset = TDBFactory.createDataset(directory);
public static final String RDFPrefix = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>";
public static final String XSDPrefix = "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>";
public static final String MYPrefix = "PREFIX myprefix: <http://www.myexample.com/mySchema#>";
public static void main(String[] args) {
UpdateTDB2 obj = new UpdateTDB2();
obj.createActionInstance();
obj.createStateInstance();
}
public static void execUpdate(String sparqlUpdateString,
GraphStore graphStore) {
UpdateRequest request = UpdateFactory.create(sparqlUpdateString);
UpdateProcessor proc = UpdateExecutionFactory.create(request,
graphStore);
proc.execute();
}
private void updateTriple(String sparqlUpdateString) {
dataset.begin(ReadWrite.WRITE);
try {
GraphStore graphStore = GraphStoreFactory.create(dataset);
execUpdate(sparqlUpdateString, graphStore);
dataset.commit();
} finally {
dataset.end();
}
}
private void createActionInstance() {
String subject = new StringBuffer("myprefix:").append("LS_1_user")
.toString();
String predicate = "rdf:type";
String object = "myprefix:Action";
String insertString = createInsertString(subject, predicate, object);
String sparqlInsertString = createSparqlString(insertString);
updateTriple(sparqlInsertString);
}
private void createStateInstance() {
String subject = new StringBuffer("myprefix:").append("LS_1_user_LicState")
.toString();
String predicate = "rdf:type";
String object = "myprefix:State";
String insertString = createInsertString(subject, predicate, object);
String sparqlInsertString = createSparqlString(insertString);
updateTriple(sparqlInsertString);
}
private String createInsertString(String subject, String predicate,
String object) {
String insertString = new StringBuffer("INSERT DATA { ")
.append(subject).append(" ").append(predicate).append(" ")
.append(object).append(" }").toString();
return insertString;
}
private String createSparqlString(String str) {
String sparqlString = StrUtils.strjoinNL(UpdateTDB2.XSDPrefix,
UpdateTDB2.RDFPrefix, UpdateTDB2.MYPrefix, str);
System.out.println(sparqlString);
return sparqlString;
}
}
Query Code
public class QueryTDB3 {
public static void main(String[] args) {
String directory = "C://myTDB//" ;
Dataset dataset = TDBFactory.createDataset(directory) ;
dataset.begin(ReadWrite.READ) ;
try
{
// Do some queries
String sparqlQueryString1 = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
String sparqlQueryString2 = "SELECT * { ?s ?p ?o }" ;
execQuery(sparqlQueryString2, dataset) ;
execQuery(sparqlQueryString1, dataset) ;
} finally
{
dataset.end() ;
}
}
public static void execQuery(String sparqlQueryString, Dataset dataset)
{
Query query = QueryFactory.create(sparqlQueryString) ;
QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
try {
ResultSet results = qexec.execSelect() ;
ResultSetFormatter.out(results) ;
} finally { qexec.close() ; }
}
}
Which version of the code are you running?
If the code you show (first part) is really being run in two separate runs (hence two JVMs), then this might be due to a known-and-fixed bug in TDB. It was only present in relative recent versions.
Please try the development version of Jena 2.7.4-SNAPSHOT.
I am trying to retrieve different kind of metadata of my Oracle DB from Java code (using basic JDBC). For example, if I want to retrieve the list of tables with _FOO suffix, I can do something like:
Connection connection = dataSource.getConnection();
DatabaseMetaData meta = connection.getMetaData();
ResultSet tables = meta.getTables(connection.getCatalog(), null, "%_FOO", new String[] { "TABLE" });
// Iterate on the ResultSet to get information on tables...
Now, I want to retrieve all the sequences from my database (for example all sequence named S_xxx_FOO).
How would I do that, as I don't see anything in DatabaseMetaData related to sequences?
Do I have to run a query like select * from user_sequences ?
Had the same question. It's fairly easy. Just pass in "SEQUENCE" into the getMetaData().getTables() types param.
In your specific case it would be something like:
meta.getTables(connection.getCatalog(), null, "%_FOO", new String[] { "SEQUENCE" });
You can't do this through the JDBC API, because some databases (still) do not support sequences.
The only way to get them is to query the system catalog of your DBMS (I guess it's Oracle in your case as you mention user_sequences)
You can use the hibernate dialect api for retrieving sequence Name. see : http://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/dialect/Dialect.html
From below example, you can see how to use dialect to get sequence names
public static void main(String[] args) {
Connection jdbcConnection = null;
try {
jdbcConnection = DriverManager.getConnection("", "", "");
printAllSequenceName(jdbcConnection);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(jdbcConnection != null) {
try {
jdbcConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void printAllSequenceName(Connection conn) throws JDBCConnectionException, SQLException {
DialectResolver dialectResolver = new StandardDialectResolver();
Dialect dialect = dialectResolver.resolveDialect(conn.getMetaData());
if ( dialect.supportsSequences() ) {
String sql = dialect.getQuerySequencesString();
if (sql!=null) {
Statement statement = null;
ResultSet rs = null;
try {
statement = conn.createStatement();
rs = statement.executeQuery(sql);
while ( rs.next() ) {
System.out.println("Sequence Name : " + rs.getString(1));
}
}
finally {
if (rs!=null) rs.close();
if (statement!=null) statement.close();
}
}
}
}
If you don't desire to use hibernate, then you have to crate custom sequential specific implementation.
Sample code for custom implementation
interface SequenceQueryGenerator {
String getSelectSequenceNextValString(String sequenceName);
String getCreateSequenceString(String sequenceName, int initialValue, int incrementSize);
String getDropSequenceStrings(String sequenceName);
String getQuerySequencesString();
}
class OracleSequenceQueryGenerator implements SequenceQueryGenerator {
#Override
public String getSelectSequenceNextValString(String sequenceName) {
return "select " + getSelectSequenceNextValString( sequenceName ) + " from dual";
}
#Override
public String getCreateSequenceString(String sequenceName,
int initialValue, int incrementSize) {
return "create sequence " + sequenceName + " start with " + initialValue + " increment by " + incrementSize;
}
#Override
public String getDropSequenceStrings(String sequenceName) {
return "drop sequence " + sequenceName;
}
#Override
public String getQuerySequencesString() {
return "select sequence_name from user_sequences";
}
}
class PostgresSequenceQueryGenerator implements SequenceQueryGenerator {
#Override
public String getSelectSequenceNextValString(String sequenceName) {
return "select " + getSelectSequenceNextValString( sequenceName );
}
#Override
public String getCreateSequenceString(String sequenceName,
int initialValue, int incrementSize) {
return "create sequence " + sequenceName + " start " + initialValue + " increment " + incrementSize;
}
#Override
public String getDropSequenceStrings(String sequenceName) {
return "drop sequence " + sequenceName;
}
#Override
public String getQuerySequencesString() {
return "select relname from pg_class where relkind='S'";
}
}
public void printSequenceName (SequenceQueryGenerator queryGenerator, Connection conn) throws SQLException {
String sql = queryGenerator.getQuerySequencesString();
if (sql!=null) {
Statement statement = null;
ResultSet rs = null;
try {
statement = conn.createStatement();
rs = statement.executeQuery(sql);
while ( rs.next() ) {
System.out.println("Sequence Name : " + rs.getString(1));
}
}
finally {
if (rs!=null) rs.close();
if (statement!=null) statement.close();
}
}
}
public static void main(String[] args) {
Connection jdbcConnection = null;
try {
jdbcConnection = DriverManager.getConnection("", "", "");
printAllSequenceName(new OracleSequenceQueryGenerator(), jdbcConnection);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(jdbcConnection != null) {
try {
jdbcConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Given that recent versions of the Oracle JDBC drivers (e.g. 12.1.0.2) don't return sequence information when you call DatabaseMetaData#getTables with types set to ["SEQUENCE"], your best bet is to run the necessary query yourself, e.g.:
SELECT o.owner AS sequence_owner,
o.object_name AS sequence_name
FROM all_objects o
WHERE o.owner LIKE 'someOwnerPattern' ESCAPE '/'
AND o.object_name LIKE 'someNamePattern' ESCAPE '/'
AND o.object_type = 'SEQUENCE'
ORDER BY 1, 2
... where someOwnerPattern and someNamePattern are SQL patterns like the ones you'd use with the LIKE operator (e.g. % matches anything).
This is basically the same as the query run by the driver itself, except that it queries for objects of type SEQUENCE.