Java Excel Manipulation - java

Hello i a am curently trying to read an excel file and manipulate it as a database. I wrote the following code whitch i supposed to fetch the first row of the datasheet and print it
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
public class ExcelReader {
public static void main( String [] args ) {
Connection c = null; Statement stmnt = null;
try
{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
//using DSN connection. Here qa is the name of DSN
//c = DriverManager.getConnection( "jdbc:odbc:qa", "", "" );
//using DSN-less connection
c = DriverManager.getConnection( "jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=C:/Users/Μιχάλης/Documents/mike1.xls");
stmnt = c.createStatement();
String query = "select * from [Ledis$] ;";
ResultSet rs = stmnt.executeQuery( query );
while( rs.next() )
{
System.out.println(rs.getString(1));
}
}
catch( Exception e )
{
//System.err.println( e );
}
finally
{
try
{
stmnt.close();
c.close();
}
catch( Exception e )
{
System.err.println( e );
}
}
}
}
When i execute the upper code i get the following print out
90-02-00-0000-2000
90-02-00-0000-2400
90-02-00-0000-2500
90-02-00-0000
90-02-00
90-02
90-06-00-0000-6000
90-06-00-0000-6100
90-06-00-0000-6200
90-06-00-0000-6300
90-06-00-0000-6400
90-06-00-0000-6500
90-06-00-0000-6600
90-06-00-0000
90-06-00
90-06
null
The problem is that in the last column the price that was supposed to be printed is 90 instead of null.
Does anybody have any idea of what is happening;

Related

Retrieve sql date and store in java object which expects localDate

I have to retrieve a Date from an oracle database and store it into a java object as localDate. This is the code I have tried:
public Sample findSampleById(Integer sampleId) {
// TODO Auto-generated method stub
PreparedStatement pStmt = null;
ResultSet rs = null;
Sample sample = new Sample();
String sql = "select * from sample where sampleid =" + sampleId;
try {
pStmt = getConnection().prepareStatement(sql);
rs = pStmt.executeQuery();
while(rs.next()) {
sample.setSampleId(rs.getInt("sampleid"));
sample.setSampleKindId(rs.getInt("samplekindid"));
sample.setExpirationDate(rs.getDate("expirationdate").toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
}
} catch (SQLException e) {
throw new DataException(e);
}
return sample;
}
Instead of this sample.setExpirationDate(rs.getDate("expirationdate").toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
I have also tried this
java.sql.Date retrieved = java.sql.Date.valueOf(rs.getString("expirationDate")); sample.setExpirationDate(retrieved.Date());
Sample is a class with int sampleId, int sampleKindId and LocalDate expirationDate
My JUnit Test for the method tells me in the line where I ask for the expiration date that it throws an exception. Do I do anything wrong with the conversion?
Method getDate, in interface java.sql.ResultSet, returns an instance of java.sql.Date.
You just need to call method toLocalDate on the value returned by method getDate.
I don't have your database so I simply tried selecting SYSDATE from the DUAL database table in Oracle. The following code worked fine.
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.LocalDate;
public class JdbcTest {
public static void main(String[] args) {
String url = "jdbc:oracle:thin:..."; // Replace with your appropriate URL
try (Connection conn = DriverManager.getConnection(url);
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select sysdate from dual")) {
if (rs.next()) {
Date sysdate = rs.getDate(1);
LocalDate ld = sysdate.toLocalDate();
System.out.println("LocalDate: " + ld);
System.out.println(" sysdate: " + sysdate);
}
}
catch (Exception x) {
x.printStackTrace();
}
}
}
Refer to Convert between LocalDate and sql.Date

Unable to get column name and column lable in sql server result set meta data

Can anybody help me to get actual column name and its alias using ResultSetMetaData by connecting to sqlserver database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
class MysqlCon {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=alcoa", "sa", "test");
Statement stmt = con.createStatement();
String query = "SELECT std_code as \"Student code\" from Student ";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsm =rs.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
System.out.println(rsm.getColumnLabel(i) + "--" + rsm.getColumnName(i));
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
output
Student code--Student code
Above code works as expected in other database like mysql and oracle.
I checked code for SQLServerResultSetMetaData. Both methods getColumnLabel and getColumnName are identical.
abzycdxw65, has raised same issue on their github account. it is closed.
Is there any way to get following output:
Student code--std_code
If I get your question you can try the followings to retrieve column names
select name from sys.columns

Java Oracle database connection error

I am new to Java and Oracle. I am trying to make an application that lists serial numbers of a product and when you click on a product's serial number from the list, it shows the other column informations from the database in a textbox. I have a form named CRUD.I am using Oracle 10g. Code is here:
package project1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class CRUD extends javax.swing.JFrame {
Connection connection = null;
public CRUD() {
try {
initComponents();
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
String serverName = "192.168.0.36";
String portNumber = "1521";
String sid = "XE";
String url = "jdbc:oracle:thin:#"+serverName+":"+portNumber+":"+sid;
String userName = "HR";
String password = "hr";
try {
connection = DriverManager.getConnection(url,userName,password);
} catch (SQLException ex) {
Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
}
try {
String temp="";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SERI_NO FROM KART");
while(rs.next()) // dönebildiği süre boyunca
{
String s = rs.getString("SERI_NO") ; //kolon isimleri oluşturuldu
temp+=s+"_";
}
Object [] tem_obj;
tem_obj=temp.split("_");
listOgrenciler.setListData(tem_obj);
} catch (SQLException ex) {
Logger.getLogger(edit.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
}
listOgrenciler.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent arg0) {
if (!arg0.getValueIsAdjusting()) {
try {
Statement stmtx = connection.createStatement();
Object[] sss=listOgrenciler.getSelectedValues();
String swhere="" ;
for (int i = 0; i < sss.length; i++) {
swhere+=sss[i].toString()+",";
}
swhere=swhere.substring(0,swhere.length()-1);
ResultSet rsx = stmtx.executeQuery("SELECT * FROM KART where SERI_NO in ("+swhere+")") ;
String temp="";
Object [] tem_obj;
tem_obj=temp.split("_");
String ara="";
for (int i = 0; i < tem_obj.length; i++) {
ara+=tem_obj[i].toString()+"\n";
}
texttoarea.setText(ara);
} catch (SQLException ex)
{
Logger.getLogger(edit.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
Errors i get are here:
20.Şub.2014 11:22:11 project1.CRUD$1 valueChanged
SEVERE: null
java.sql.SQLSyntaxErrorException: ORA-00904: "SNS080961097": invalid identifier
.....
at project1.CRUD$1.valueChanged(CRUD.java:78)
......
As I said before, I am new to both Java and Oracle. If the errors are so obvious don't laugh:)
Your this query
ResultSet rsx = stmtx.executeQuery("SELECT * FROM KART where SERI_NO in ("+swhere+")") ;
should be like this:
ResultSet rsx = stmtx.executeQuery("SELECT * FROM KART where SERI_NO in ('"+swhere+"')") ;
Actually there is no problems with you connection step to Oracle DB, its connected successfully, Your problem is within the query. make sure that you have a SERI_NO column in your KART table.
i suggest you to RUN the both same queries in you code from any SQL client such SQLDeveloper and see what these queries retrieve.
Observe this statement once,
swhere=swhere.substring(0,swhere.length()-1);
replace the above statement with the following
shere=swhere.substring(0,swhere.length()-2);
Because an extra comma(,) is included in your sql statement.
There is no issue with your connection.
Please add some logging to your code and you will know exactly where the error is throwing.
I guess the error is throwing in this line..
SELECT * FROM KART where SERI_NO in ("+swhere+")
You have to specify this as a string with '',where you actual select should look like below.
SELECT * FROM KART where SERI_NO in ('ABC','XCV');
so please check with this one check the value of the "swhere"

Reading Visual Foxpro Data From Java using ODBC

I am trying to query a dbf table from my Java application. I put in reference this thread
I created a system data source using the ODBC Data Source Administrator, I set the data source name to be VFPDS and set the database type to .DBC finaly i set the path to the .dbc file.
the following is my java code:
import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
// Import custom library containing myRadioListener
import java.sql.DriverManager;
public class testodbc {
public static void main( String args[] )
{
try
{
// Load the database driver
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;
// Get a connection to the database
Connection conn = DriverManager.getConnection( "jdbc:odbc:VFPDS" ) ;
// Print all warnings
for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() )
{
System.out.println( "SQL Warning:" ) ;
System.out.println( "State : " + warn.getSQLState() ) ;
System.out.println( "Message: " + warn.getMessage() ) ;
System.out.println( "Error : " + warn.getErrorCode() ) ;
}
// Get a statement from the connection
Statement stmt = conn.createStatement() ;
// Execute the query
ResultSet rs = stmt.executeQuery( "SELECT * FROM pmsquoteh" ) ;//code crashes here
// Loop through the result set
while( rs.next() )
System.out.println( rs.getString(1) ) ;
// Close the result set, statement and the connection
rs.close() ;
stmt.close() ;
conn.close() ;
}
catch( SQLException se )
{ se.printStackTrace();
System.out.println( "SQL Exception:" ) ;
// Loop through the SQL Exceptions
while( se != null )
{ se.printStackTrace();
System.out.println( "State : " + se.getSQLState() ) ;
System.out.println( "Message: " + se.getMessage() ) ;
System.out.println( "Error : " + se.getErrorCode() ) ;
se = se.getNextException() ;
}
}
catch( Exception e )
{
System.out.println( e ) ;
}
}
}
I got this exception :
java.sql.SQLException: [Microsoft][ODBC Visual FoxPro Driver]Not a table.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
at UsingButtons.main(testodbc.java:38)
SQL Exception:
State : S0002
Message: [Microsoft][ODBC Visual FoxPro Driver]Not a table.
Error : 123
I am sure that the table pmsquoteh exits in the database and my machine is a 64 bit machine.
What am i doing wrong ? I would appreciate specific answers.
I was able to access a FoxPro table with the jdbc-odbc bridge on Windows 7 but it took a number of steps. I already had the VFP driver installed, and I don't remember where I downloaded it from, so I don't have a link for that.
I copied the code from a jbdc:odbc example here: http://www.java2s.com/Code/Java/Database-SQL-JDBC/SimpleexampleofJDBCODBCfunctionality.htm.
The DriverManager.getConnection method takes a database URL. To create a URL you need to use the ODBC manager. Unfortunately for me, the ODBC manager that I could get to through the control panel only worked for 64 bit data sources. I am not aware of a 64 bit foxpro driver.
To generate a 32 bit DSN you need to run the 32 bit ODBC manager: odbcad32.exe. My machine had several copies. I ran the one from C:\Windows\SysWOW64. Go to the System DSN tab and select the Microsoft Visual Foxpro Driver. When you click finish, you will get a dialog that asks for a Data Source Name, description and path to the FoxPro database or tables. You also have to specify whether you want to connect to a .dbc or a free table directory. Your error message makes me wonder if you had the wrong option selected on your DSN.
The database URL I passed in to the getConnection method was "jdbc:odbc:mydsnname".
After I ran this, I received an error:
[Microsoft][ODBC Driver Manager] The specified DSN contains an
architecture mismatch between the Driver and Application
This was because I was using a 64 bit JVM with a 32 bit DSN. I downloaded a 32 bit JVM and was able to use it to run my sample class.
I do not know if there is a switch you can set on a 64 bit JVM to tell it to run as 32 bit.
I used the JDBC driver from here:
http://www.csv-jdbc.com/relational-junction/jdbc-database-drivers-products/new-relational-junction-dbf-jdbc-driver/
Works fine for me. In testing so far (about an hour), it reads MEMO files and seems to have had no issues with either DBC-containted tables or free DBFs.
Not sure how much this driver costs. The client will only probably pay $100 max since VFP is beyond obsolete.
I am using javadbf-0.4.0.jar for last six month without and problem.I will post my Java class and main program.
package foxtablereader.src;
import java.sql.Connection;
import java.sql.SQLException;
import sun.jdbc.rowset.CachedRowSet;
/**
*
* #author kalimk
*/
public class DbfMain {
static CachedRowSet crs;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws SQLException {
DbfConnection foxconn = new DbfConnection();
Connection connection = null;
String inputTablePath = "c:\\vfp_table\\";
connection = foxconn.connection(inputTablePath);
String query = "SELECT * FROM TrigExport2.dbf ";
crs = foxconn.select(query, connection);
//crs = ft.query(query, inputTablePath);
System.out.println(" Size " + crs.size());
while (crs.next()) {
System.out.println("DESC " + crs.getString("Serialnum") + " " + crs.getString("cmailcode"));
}
inputTablePath = "C:\\sourcecode\\FoxTableReader\\";
connection = foxconn.connection(inputTablePath);
query = "SELECT * FROM TrigExports.dbf ";
crs = foxconn.select(query, connection);
System.out.println(" Size " + crs.size());
int z = 1;
while (crs.next()) {
System.out.println(z++ + " " + crs.getString("Serialnum") + " " + crs.getString("cmailcode"));
}
inputTablePath = "C:\\sourcecode\\FoxTableReader\\";
connection = foxconn.connection(inputTablePath);
String queryinsert = "insert into Mcdesc (Desc,Mailcode,Del_type,Column1) values ('Kalim','KHAN', 'ERUM','KHAN')";
foxconn.insertUpdate(queryinsert, connection);
inputTablePath = "C:\\sourcecode\\FoxTableReader\\";
connection = foxconn.connection(inputTablePath);
String queryupdate = "update Mcdesc set Column1= 'Sadiqquie' where Desc = 'Kalim'";
foxconn.insertUpdate(queryupdate, connection);
}
}
package foxtablereader.src;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.jdbc.rowset.CachedRowSet;
/**
*
* #author kalimk
*/
public class DbfConnection {
public Connection connection(String inputTablePath) throws SQLException {
Connection con = null;
//String jdbURL = "jdbc:DBF:/C:\\vfp_table\\";
String jdbURL = "jdbc:DBF:/" + inputTablePath;
Properties props = new Properties();
props.setProperty("delayedClose", "0");
try {
Class.forName("com.caigen.sql.dbf.DBFDriver");
try {
con = DriverManager.getConnection(jdbURL, props);
} catch (SQLException ex) {
Logger.getLogger(DbfConnection.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(DbfConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
public CachedRowSet select(String cQuery, Connection con) {
CachedRowSet crs = null;
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(cQuery);
crs = new CachedRowSet();
crs.populate(rs);
stmt.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return crs;
}
public boolean insertUpdate(String cQuery, Connection con) {
boolean crs = false;
try {
PreparedStatement pStmnt = con.prepareStatement(cQuery);
crs = pStmnt.execute();
pStmnt.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return crs;
}
public int insertUpdateCount(String cQuery, Connection con) {
int count = 0;
try {
Statement stmt = con.createStatement();
count = stmt.executeUpdate(cQuery);
System.out.println("Number of rows updated in database = " + count);
stmt.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return count;
}
public int insertUpdateCount2(String cQuery, Connection con) {
int count = 0;
boolean crs = false;
try {
PreparedStatement pStmnt = con.prepareStatement(cQuery);
count = pStmnt.executeUpdate(cQuery);
pStmnt.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return count;
}
public static void DBDisconnect(Connection DBCon) {
try {
if (DBCon != null) {
DBCon.close();
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
try {
DBCon.close();
//System.err.println("Fimally is always executed");
} catch (SQLException ex) {
Logger.getLogger(DbfConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}

selecting data from cassandar using cql

i am using cassandra-jdbc to perform the operation on data in cassandra but when i run this simple program i get exception.
this is my code:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.*;
import javax.sql.*;
public class Operations
{
public static void main(String[] args){
try
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/temp");
String qry = "select name FROM cql";
Statement smt = con.createStatement();
ResultSet resultSet = smt.executeQuery(qry);
System.out.println(resultSet);
while(resultSet.next())
{
System.out.println(resultSet);
}
}
catch(Exception e)
{
System.out.println(" : "+e.getMessage());
}
}
}
i got :cannot parse 'name' as hex bytes
Try:
import static org.apache.cassandra.utils.Hex.bytesToHex;
...
String name = bytesToHex("name".getBytes());
String qry = "select '" + name + "' FROM cql";

Categories