I am trying to read from excel using Fillo-1.18. Below is my code:
public static void main(String[] args) {
Fillo fillo=new Fillo();
Connection connection;
try {
connection = fillo.getConnection("C:\\Users\\Dish\\Desktop\\1.xlsx");
String strQuery="Select sum(Amount) as amnt, Run_ID from Sheet1 group by Run_ID";
Recordset recordset=connection.executeQuery(strQuery);
while(recordset.next()){
System.out.println(recordset.getField("amnt"));
}
recordset.close();
connection.close();
} catch (FilloException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It works fine for normal select clause. But when I am trying to use aggregate functions like SUM(), I am not able to access that field. Inside while I am get the following error:
com.codoid.products.exception.FilloException: amnt field is not found
at com.codoid.products.fillo.Recordset.getField(Recordset.java:163)
at ReadExcelSheetData.main(ReadExcelSheetData.java:18)
How can I resolve this?
Related
I have following Java code that creates a stored procedure. To test it I am deliberately passing it invalid sql:
public void createStoredProcedure(#NotNull final StoredProcInfo storedProcInfo, #NotNull final ColumnInfoFactory columnInfoFactory, #NotNull final Connection con) {
Statement createProcStmt = null;
try {
List<String> parameterDefinitions = Lists.newArrayList();
for (StoredProcParmInfo parmInfo : storedProcInfo.getInParameters()) {
parameterDefinitions.add(columnInfoFactory.generateParameterDefinition(parmInfo));
}
for (StoredProcParmInfo parmInfo : storedProcInfo.getOutParameters()) {
parameterDefinitions.add(columnInfoFactory.generateParameterDefinition(parmInfo));
}
String createProcSql = String.format("CREATE Procedure %s (%s) AS BEGIN %s END;", storedProcInfo.getName(), StringUtils.join(parameterDefinitions.iterator(), ","), storedProcInfo.getBody());
createProcStmt = con.createStatement();
createProcStmt.execute(createProcSql);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Closer.close(createProcStmt, logger);
}
}
The method executes successfully. And when I look in the database, I see that a stored procedure was created but marked as an invalid object:
And the error is that an INTO clause was expected in the body of the procedure:
Why was an SQLException not thrown when the code that created the procedure was executed? Is this an Oracle driver setting? I have searched online but not found any helpful information.
I am using following code to iterate through a database's documents.
public void readDataStore() throws IOException {
Query query = document_datastore.find(DocumentPojo.class);
List<DocumentPojo> documentPojos = query.asList();
documentPojos.forEach(obj -> {
try {
System.out.println(obj.getDocid());
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
Currently the DB has not more than 100 documents but in future it can have ~100000 documents. I suspect then it may run into performance issues?
DocumentPojo is the class that I map the results to. I am using Java 8 and Morphia.
How should I solve this issue?
Use query.fetch() to get the MorphiaIterator and then handle each document as you get it. It won't pull them all in to memory at once allowing you to process your hundred thousand+ documents.
One way of implementing #evanchooly's answer:
public void readDataStore() throws IOException {
final Query query = document_datastore.find(DocumentPojo.class);
query.fetch().forEach(obj -> {
try {
System.out.println(obj.getDocid());
} catch (final IOException e) {
e.printStackTrace();
}
});
}
Hi below code form from my Derby embedded example...
when i run on my pc(developed)it run smoothly.
And then i export as jar file and run on another pc .it throws an exception table already exists.
How can i create table only once on any pc
public class Main {
public static void main(String[] args) throws SQLException {
final String driver="org.apache.derby.jdbc.EmbeddedDriver";
final String url="jdbc:derby:db/testdb";
try {
Class.forName(driver);
Connection connection=DriverManager.getConnection(url);
//connection.createStatement().execute("create table channels(channel varchar(20),topic varchar(20))");
// connection.createStatement().execute("insert into channels (channel,topic) values('hbo','action')");
// System.out.println("saved");
PreparedStatement preStmt=connection.prepareStatement("select * from channels");
ResultSet set=null;
set=preStmt.executeQuery();
while(set.next()){
System.out.print(set.getString(1));
System.out.println(set.getString(2));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Also how to configure same issue on hibernate.cfg.xml file...!!
You can check to see if the table already exists before you create it.
Use the DatabaseMetadata calls to examine the structure of the database after you connect to it.
See: http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html
You can check before every creation check it in DB metadata:
Methods looks like following:
ResultSet result = databaseMetaData.getTables(
catalog, schemaPattern, tableNamePattern, types );
Abd you can use it as following:
ResultSet result = databaseMetaData.getTables(
null, null, TABLE_NAME, null );
Exactly like here I want to disable the foreign key check when modifying the database.
However I can't get it to work. If I try this:
jdbc:sqlserver://myserver:1433?sessionVariables=FOREIGN_KEY_CHECKS=0
It will try to take the whole 1433?sessionVariables=FOREIGN_KEY_CHECKS=0 as a port number.
Trying it like this:
jdbc:sqlserver://myserver:1433;FOREIGN_KEY_CHECKS=0
doesn't help either, it will setup the connection but throw a foreign-key constraint violation.
I already looked through the Microsoft API on the JDBC driver and googled, but it wasn't any help.
Does someone know a solution?
It seems like this is not possible with MSSQL. The spec for the URL is
jdbc:sqlserver://[serverName[\instanceName][:portNumber]];property=value[;property=value]]
No session variables can be added here, at least it seems to me.
My solution is to en- and disable the database constraints using a statement.
public static void resetDatabase(String dataSetFilename) throws DatabaseException {
IDatabaseConnection connection = null;
try {
connection = getDatabaseConnection();
disableDatabaseConstraints(connection);
executeDatabaseReset(connection, dataSetFilename);
} catch (Exception ex) {
throw new DatabaseException(ex);
} finally {
enableDatabaseConstraints(connection);
}
}
private static void disableDatabaseConstraints(IDatabaseConnection connection) throws DatabaseException {
try {
Statement disableConstraintsStatement = connection.getConnection().createStatement();
disableConstraintsStatement.execute("exec sp_MSforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT ALL\"");
disableConstraintsStatement.execute("exec sp_MSforeachtable \"ALTER TABLE ? DISABLE TRIGGER ALL\"");
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
}
private static void enableDatabaseConstraints(IDatabaseConnection connection) throws DatabaseException {
try {
Statement enableConstraintsStatement = connection.getConnection().createStatement();
enableConstraintsStatement.execute("exec sp_MSforeachtable \"ALTER TABLE ? CHECK CONSTRAINT ALL\"");
enableConstraintsStatement.execute("exec sp_MSforeachtable \"ALTER TABLE ? ENABLE TRIGGER ALL\"");
} catch (SQLException ex) {
throw new DatabaseException(ex);
}
}
I am testing QueryDSL against the World database in MySql. I can retrieve the data as a List, but I cannot get it to return as a List. I am querying via SQL, nothing else. This is what I have.
private void getSomething(Connection connection) {
QCountry country = QCountry.country;
SQLTemplates dialect = new HSQLDBTemplates();
SQLQuery query = new SQLQueryImpl(connection, dialect);
//List<Object[]> countries = query.from(country).list(country.all());
List<QCountry> countries = query.from(country).list(country);
System.out.println(countries);
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get this error:
java.lang.IllegalArgumentException: RelationalPath based projection can only be used with generated Bean types
You need to generate bean types as described here http://blog.mysema.com/2011/01/querying-in-sql-with-querydsl.html under Bean class generation.