load csv file to oracle database - java

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.

Related

Error message "java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver" is shown when run java on command line

I am trying to run the java program on command line but this message is shown:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
Then I have searched a few hours and most solutions are about checking the
Java version,
importing the JDBC jar and
editing the classpath
For 1, I checked the java version I am using is 1.8
So for 2, I have downloaded the sqljdbc41.jar , put the jar into a lib folder, and run the command with:
java -cp C://Testing/lib/* -classpath . sampleJava
For 3, I have edited the classpath to C://Testing/lib/sqljdbc41.jar
Anyone knows do I miss something so that the same error message still shows?
Below is the sample program I run:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
public class sampleJava {
int x = 5;
public static void main(String[] args) {
sampleJava myObj = new sampleJava();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
System.err.println(e);
System.out.println(e.toString());
e.printStackTrace();
}
finally {
System.out.println("Done");
}
System.out.println(myObj.x);
}
}
This should help
java -cp C:/Testing/lib/*; sampleJava
or
java -cp C:/Testing/lib/sqljdbc41.jar; sampleJava

How to resolve a Local Converter issue with documents4j

document4j looks like a great api and I'd love to use it. I just want to bulk convert docx to pdf on my mac (with Microsoft office installed).
I have written this but I get the error that the LocalConverter cannot be resolved. What am I doing wrong? Have I imported the correct jars?
package Input;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.concurrent.Future;
import org.xml.sax.SAXException;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
public class TBB {
public static FileInputStream convert(InputStream docxInputStream) throws FileNotFoundException {
FileInputStream inputStream = null;
try (OutputStream outputStream = new FileOutputStream(new File("/Users/sebastianzeki/mydoc.docx"))) {
IConverter converter = LocalConverter.builder().build();
converter
.convert(docxInputStream).as(DocumentType.DOCX)
.to(outputStream).as(DocumentType.PDF)
.prioritizeWith(1000).schedule();
inputStream = new FileInputStream("/Users/sebastianzeki/mydoc.docx");
} catch (Exception e) {
e.getMessage();
}
return inputStream;
}
}
documents4j is not compatible with Mac. Look at your stacktrace and you will find something like: com.documents4j.throwables.ConverterAccessException: Unable to run script: /Applications/Tomcat-9.0.1/temp/1564683313105-0/word_start775650809.vbs Documents4j is running a generated vbScript under the hood. There is no way for mac to run vbScript as far as I know. I had to install a Windows vm with Word installed on my server and use the documents4j remote api to call into the windows vm to do the conversions.

How can I set the directory of a MongoDB database in a Java application?

I recently decided to learn the foundamentals of using MongoDB in Java applications but I have some problems and doubts to resolve. I hope someone can help me.
I wrote a little Java application to read and write data in a local Mongo database (I'm using mongo-java-driver-3.3.0.jar on Windows 10).
I have installed MongoDB in the directory C:\Program Files\MongoDB.
Can anyone tell me if is possible to create my test database in a specific directory (for example D:\Database)? Thank you.
package test;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoDatabase;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC
{
public static void main( String args[] )
{
try
{
// Connection to the MongoDB server
MongoClient mongoClient = new MongoClient("localhost" , 27017);
// Connection to the database
MongoDatabase db = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
}
catch(Exception e)
{
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

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

Full Dataset Export blank dataset

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.

Categories