Full Dataset Export blank dataset - java

I have a database in libreoffice Base (Debian) which I need to export the tables as an xml file. I have created a piece of Eclipse Java code which is as follows:
package NewDB;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.dataset.DataSetException;
public class ExtractTestDataSet {
public static void main(String[] args) throws Exception {
// database connection
Class driverClass = Class.forName("org.hsqldb.jdbcDriver");
Connection jdbcConnection = DriverManager.getConnection "jdbc:hsqldb:/home/debian/Documents/database.odb", "sa", "");
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
// full database export
IDataSet fullDataSet = connection.createDataSet();
FlatXmlDataSet.write(fullDataSet, new FileOutputStream("/home/debian/Documents/fulldataset.xml"));
}
}
After looking at the DBunit pages and other various sites this code should be correct; the database is populated, the connections are valid, there are no warnings or errors in the code, however when the xml file is created the only content is as follows:
<?xml version='1.0' encoding='UTF-8'?>
<dataset/>
Does anyone have any ideas as to why the dataset is not being exported?
Thanks

Turns out that the .odb database was connected to a different backend, explaining the blank dataset.

Related

I can't connect java with hive

I have installed hadoop-2.3.0 and successfully configured hive on my machine ..
i have windows 7 on my machine ..
now i 've created so simple project to just connect to hive driver ..
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class Hive_java{
private static String driver = "org.apache.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName(driver);
Connection connect =
DriverManager.getConnection("jdbc:hive2://localhost:10000/data", "", ""); //connecting to default database
}
}
and added these jars
now i have this error which can't solve it for some days .. connection refused
please tell me what can i do as am beginner in hive .. thanks in advance

Best way to connect java swing app to ms access db on a shareserver?

Currently im developing a java swing application that I'd like to serve as the GUI for CRUD operations on a MS access database. Currently, everyone on the team that will be using this application updates a spreadsheet on a shareserver. They'd like to switch over to a UI that better suits their purposes, and transition the spreadsheet to a database.
I'm planning on putting an executable jar and the ms access database file on the shareserver. This is where the jar will be accessed.
I don't want users to have to be messing with ODBC settings. Is there a library that can help with this?
UPDATE: Shailendrasingh Patil's suggestion below worked best for me. This took me a little bit of research and the setup was a bit confusing. But I eventually got everything working the way I was hoping. I used Gradle to pull in the necessary dependencies to use UcanAccess.
The following is a snippet from my DatabaseController class:
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DatabaseController {
public DatabaseController() {}
public void addOperation(String date, String email, String subject, String body) {
try{
Connection con = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\user\\Desktop\\TestDatabase.accdb;jackcessOpener=CryptCodecOpener","user", "password");
String sql = "INSERT INTO Email (Date_Received, Email_Address, Subject, Message) Values " +
"('"+date+"'," +
"'"+email+"'," +
"'"+subject+"'," +
"'"+body+"')";
Statement statement = con.createStatement();
statement.execute(sql);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(),"Error",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
}
The following class is also required:
import java.io.File;
import java.io.IOException;
import com.healthmarketscience.jackcess.CryptCodecProvider;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;
import net.ucanaccess.jdbc.JackcessOpenerInterface;
public class CryptCodecOpener implements JackcessOpenerInterface {
public Database open(File fl,String pwd) throws IOException {
DatabaseBuilder dbd =new DatabaseBuilder(fl);
dbd.setAutoSync(false);
dbd.setCodecProvider(new CryptCodecProvider(pwd));
dbd.setReadOnly(false);
return dbd.open();
}
}
I apologize for the bad indentations.
You should use UCanAccess drivers to connect to MS-Access. It is a pure JDBC based and you don't need ODBC drivers.
Refer examples here

java.sql import not working

My .getTables and .prepareStatement are not working. I thought I only had to import the java.sql.* for these to work. Please let me know what else I need to do. Thank you for your time. It says "cannot find symbol" next to both lines and will not compile.
import edu.lcc.citp.inventory.Product;
import java.sql.DriverManager;
import javax.jms.Connection;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.jms.JMSException;
public class DatabaseProductDao implements DataAccessObject<Product> {
Connection con;
public DatabaseProductDao() throws SQLException, JMSException, ClassNotFoundException {
Class.forName("cockeb.org.apache.derby.jdbc.ClientDriver");
try (Connection con = (Connection) DriverManager.getConnection("jdbc:derby://localhost:1527/store;create=true")) {
boolean exists = con.getMetaData().getTables(null, null, "PRODUCT", null).next();
if (exists) {
System.out.println("Table Exists");
} else {
String createDml = "CREATE TABLE PRODUCT (UPC VARCHAR(25), SHORT_DETAILS VARCHAR(50), LONG_DETAILS VARCHAR(5000), PRICE DECIMAL(10,2), STOCK INTEGER, PRIMARY KEY (UPC))";
PreparedStatement createStatement = con.prepareStatement(createDml);
createStatement.execute();
}
} catch (SQLException e) {
System.out.println("Can Not Connect At This Time");
}
}
The problem is with imports.
You imported javax.jms.Connection which is obiously wrong. Just delete it.
What you wanted is Connection class from java.sql (java.sql.Connection) package.
Also I do not suggest to use wildcards (.*) in import but pick specific class you actually use. In your case:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
You need to add the following imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
instead of the one you are using
I'd suggest that you remove these lines:
import javax.jms.Connection;
import javax.jms.JMSException;
...as it's probably not the Connection class that you actually intended on importing. Your java.sql.* import should grab the correct one once you remove the lines above.
Some of your imports are wrong. You need below to make it work.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Connection;
One step ahead I would like to suggest you to have a separate class to establish the database connection. This way you don't need to repeat the same code again.
Sample code. (Do changes for this as appropriate.)
for instance have a DatabaseCon.java class in your project
package classes;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class DatabaseCon {
private static Connection c;
private static void connect()
throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "db_url/db";
c = DriverManager.getConnection(url, "username", "pass");
}
public static PreparedStatement prepareState(String sql)
throws Exception {
if (c == null) {
connect();
}
return c.prepareStatement(sql);
}
}
This can then be called by
public void yourMethod() {
PreparedStatement p = null;
try {
p = DatabaseCon.prepareState("Your_query");
............
} catch (Exception e) {
//catch it
} finally {
//do the final stuff
}
}
Note This way is good if it is a fairly big project as you've mentioned.
You have imported a few wrong classes for use.
import java.sql.DriverManager;
import javax.jms.Connection;
import java.sql.*;
import javax.jms.JMSException;
The jms imports are of no use; you have imported them in vain, which is causing issues in your program.
The main import required is java.sql.*,
the application will work correctly if you just remove the jms imports.
But, the best practice to import classes is to specify the specific class from which you are using the element/method.
See here for the reason Single import vs package import

Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Could not open connection

caused by connection reset
I am trying to connect my java program to sql server 20008 r2 through hibernate but i am getting error
main class is as follows
package com.prizm;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class SecondPractice {
public static void main(String args[]){
Configuration configuration = new
Configuration().configure("hibernate.cfg.xml");
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
SessionFactorysessionFactory=configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
Student lecturer = new Student();
lecturer.setFirstname("raj");
lecturer.setLastname("kumar");
session.save(lecturer);
session.getTransaction().commit();
session.close();
}
}
So where i am making mistake, what do i need to know about this error, how to solve it
Thanks in advance
Here i have edited my question and posted the different code from the aforementioned as i am not comfortable with log4J properties so i have tried to connect my java code to database through JDBC , connection is getting done but when it comes about creating any table or any thing else related to data transfer it gives me the same error as i have mentioned.
Here is the code for JDBC along with Logger api of java (java.util.Logger)
package com.prizm;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.SimpleFormatter;
public class JKL {
public static Logger logger=Logger.getLogger(JKL.class.getName());
public static FileHandler fh=null;
public static void init(){
try{
fh=new FileHandler("logger.log",false);
}catch(Exception e){}
fh.setFormatter(new SimpleFormatter());
Logger l=Logger.getLogger("");
l.addHandler(fh);
Connection con=null;
try{
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
con=DriverManager.getConnection("jdbc:sqlserver://167.01.09.12;IntegratedSecurity=true");
if(con!=null){
System.out.println("done");
}
Statement st=con.createStatement();
st.executeUpdate("create table hi(id int,name varchar(50))");
}catch(SQLException e){l.log(Level.SEVERE,"Here is your error",e);}
}
public static void main(String args[]){
JKL.init();
}
}
and the log record that i am getting is this
]
so what should i understand from it, do i need to do something with the configuration of microsoft sql server 2008 r2 , as i have sp1 version and this piece of code is working very fine on my friend's computer.
In java 6u29 there was a bug introduced by oracle with bug id : 7103725 which restricts the SSL Connections to SQL Server 2008 and except java version 1.6.0_24 it will give the aforementioned error, to solve this problem we have to pass following property and value to java
-Djsse.enableCBCProtection=false
and as i am using eclipse the steps are as follows
RunAs>>RunConfiguration>>VMArgument and inside the block,copy this property and value, for more detail follow this link.

load csv file to oracle database

Hi I wanted to load csv file in Oracle database using java but what I am getting error like "ora-00900 invalid sql statement". I am using oracle Database 11g Enterprise Edition. So I don't understand why it doesn't accept my load statement. Any help? Thanks in advance.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class test {
public static void main(String[] args){
test t=new test();
t.inserintoDb("C:\\Users\\fiels\\2.csv");
}
public void inserintoDb(String path){
Connection conn=null;
Statement stmt=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=(Connection) DriverManager.getConnection(
"jdbc:oracle:thin:#address:orcl","user","password");
stmt=conn.createStatement();
String select1="truncate table table1";
stmt.execute(select1);
String select2="LOAD DATA INFILE'" +path+"' INTO TABLE table1 FIELDS TERMINATED BY ',' (customer_nbr, nbr)";
stmt.execute(select2);
}catch(Exception e){
e.printStackTrace();
}
}
}
Does infile works on Oracle? It seems that only on MySql.. The SQL Loader alternative is really fast. Check the official documentation to see how to config it:
As the question states that you want to use Java here is the help for calling the SQL Loader from Java. It bassically uses a Runtime but depends on the operating system:
String[] stringCommand = { "bash", "-c", "/usr/bin/sqlldr username/password#sid control=/path/to/sample.ctl"};
Runtime rt = Runtime.getRuntime();
Process proc = null;
try {
proc = rt.exec(stringCommand);
}catch (Exception e) {
// TODO something
}finally {
proc.destroy();
}
But if you just want to load some table for your personal use you wont need java. You can call it from a .bat file.

Categories