Microsoft Excel as SQL Database - java

I have followed the instructions provided in this website from content 5.3 and the code works fine.
My plan is to make a jar file (containing an interface/GUI), distribute that jar file to users, and then have them all read/write data should be from one excel file. When I place the excel file in local drive it works, but when I place the file in network folder/server, the java creates a problem:
java.exe has encountered a problem and needs to close. We are sorry
for the inconvenience.
or
Java Result: -1073741811
Any suggestions? Thank you
public class TestIntoExcel
{
public String s;
public double number;
public Date d;
public void display()throws ClassNotFoundException, SQLException
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection writeConnection = DriverManager.getConnection
("jdbc:odbc:usersavedataODBC");
writeConnection.setReadOnly(false);
Statement writeStatement = writeConnection.createStatement();
writeStatement.executeUpdate("CREATE TABLE TEST_INSERT(COL1 INT,COL2 VARCHAR(10),COL3 DATE)");
PreparedStatement writeStatement2 =
writeConnection.prepareStatement("INSERT INTO TEST_INSERT(COL1,COL2,COL3)VALUES(?,?,?)");
for(int i = 0; i<3;i++)
{
writeStatement2.setDouble(1, i);
writeStatement2.setString(2, "Row" + i);
writeStatement2.setDate(3, new java.sql.Date(new Date().getTime()));
writeStatement2.execute();
}
String query = "select *from[TEST_INSERT]";
ResultSet rset = writeStatement.executeQuery(query);
//System.out.println(rset);
while(rset.next())
{
number = rset.getDouble("COL1");
s = rset.getString("COL2");
d = rset.getDate("COL3");
System.out.println(number+"\n"+s+"\n"+d);
}
writeStatement.close();
writeStatement2.close();
writeConnection.close();

Related

Making an SQL lite DB from a CSV file in Android Studio

I got a CSV file, basically a list of cities with some codes.
In my app users write their city of birth, a list of cities appears suggesting it, when chose the city's code is used for other stuff.
Can I just move the .csv file in an Android Studio folder and just use it as a database made with sql lite?
If no, should I make the sql lite database in Android Studio (a DatabaseManager class with SqlOpenHelper and some queries if i got it), then copy the .csv? How can I just "copy" that?
EDIT: Sorry but I realized that my CSV file had too much columns and that'd be ugly and tiring to manually add the columns. So I used DB Browser for SQLite, now I got a .db file. Can I just put it in a specific database folder and querying it in my app?
Can I just move the .csv file in an Android Studio folder and just use
it as a database made with sql lite?
No.
A sqlite database, i.e. the file, has to be formatted so that the SQLite routines can access the data enclosed therein. e.g. the first 16 bytes of the file MUST BE SQLite format 3\000 and so on, as per Database File Format
If no, should I make the sql lite database in Android Studio (a
DatabaseManager class with SqlOpenHelper and some queries if i got
it), then copy the .csv?
You have various options e.g. :-
You could copy the csv file into an appropriate location so that it will be part of the package (e.g. the assets folder) and then have a routine to generate the appropriate rows in the appropriate table(s). This would require creating the database within the App.
You could simply hard code the inserts within the App. Again this would require creating the database within the App.
You could use an SQLite Tool to create a pre-populated database, copy this into the assets folder (assets/databases if using SQLiteAssetHelper) and copy the database from the assets folder. No need to have a csv file in this case.
Example of option 1
As an example that is close to option 1 (albeit that the data isn't stored in the database) the following code extracts data from a csv file from the assets folder.
This option is used in this case as the file changes on an annual basis, so changing the file and then distributing the App applies the changes.
The file looks like :-
# This file contains annual figures
# 5 figures are required for each year and are comma seperated
# 1) The year to which the figures are relevant
# 2) The annualised MTAWE (Male Total Average Weekly Earnings)
# 3) The annual Parenting Payment Single (used to determine fixed assessment)
# 4) The fixed assessment annual rate
# 5) The Child Support Minimum Annual Rate
# Lines starting with # are comments and are ignored
2006,50648,13040,1040,320
2007,52073,13315,1102,330
2008,54756,13980,1122,339
2009,56425,13980,1178,356
2010,58854,14615,1193,360
2011,61781,15909,1226,370
2012,64865,16679,1269,383
2013,67137,17256,1294,391
2014,70569,18197,1322,399
2015,70829,18728,1352,408
2016,71256,19011,1373,414
2017,72462,19201,1390,420
2018,73606,19568,1416,427
It is stored in the assets folder of the App as annual_changes.txt The following code is used to obtain the values (which could easily be added to a table) :-
private void BuildFormulaValues() {
mFormulaValues = new ArrayList<>();
mYears = new ArrayList<>();
StringBuilder errors = new StringBuilder();
try {
InputStream is = getAssets().open(formula_values_file);
BufferedReader bf = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = bf.readLine()) != null ) {
if (line.substring(0,0).equals("#")) {
continue;
}
String[] values = line.split(",");
if (values.length == 5) {
try {
mFormulaValues.add(
new FormulaValues(
this,
Long.parseLong(values[0]),
Long.parseLong(values[1]),
Long.parseLong(values[2]),
Long.parseLong(values[3]),
Long.parseLong(values[4])
)
);
} catch (NumberFormatException e) {
if (errors.length() > 0) {
errors.append("\n");
}
errors.append(
this.getResources().getString(
R.string.invalid_formula_value_notnumeric)
);
continue;
}
mYears.add(values[0]);
} else {
if (errors.length() > 0) {
errors.append("\n");
errors.append(
getResources().getString(
R.string.invalid_formula_value_line)
);
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (errors.length() > 0) {
String emsg = "Note CS CareCalculations may be inaccurate due to the following issues:-\n\n" +
errors.toString();
Toast.makeText(
this,
emsg,
Toast.LENGTH_SHORT
).show();
}
}
Try this for adding the.csv info to your DB
FileReader file = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(file);
String line = "";
String tableName = "TABLE_NAME";
String columns = "_id, name, dt1, dt2, dt3";
String str1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
String str2 = ");";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
StringBuilder sb = new StringBuilder(str1);
String[] str = line.split(",");
sb.append("'" + str[0] + "',");
sb.append(str[1] + "',");
sb.append(str[2] + "',");
sb.append(str[3] + "'");
sb.append(str[4] + "'");
sb.append(str2);
db.execSQL(sb.toString());
}
db.setTransactionSuccessful();
db.endTransaction();

Problems with characters when getting data from Mysql

I have a problem getting data previously recorded with my java program fronted in a Mysql Database. I checked both mysql and Netbeans and the encoding is utf-8 but I still have this kind of problem.
Any tips ??
I'm on mac with netbeans 8.2
My application shows the data like this:
MySQL shows the data with no issues:
The question is not precise enough, hence some points you might try.
Add those statements in your java frontend application, after database is connected, before you INSERT any data:
SET character_set_connection="utf8"
SET character_set_client="utf8"
SET character_set_database="utf8"
SET character_set_results="utf8"
SET character_set_server="utf8"
SET character_set_system="utf8"
Probably you won't need them all; feel free to experiment which ones do the trick.
You may also log into a MySQL console and see actual settings by issuing a command:
mysql> show variables like '%character_set%';
Ok, I resolved it.
basically It was a problem about Column data in Mysql that it was BLOB...I already tried to change in LONGTEXT, but even if all Database was in UTF-8 if I changed only type of content it wasn't enough !.
I Had to change both type of collation, Database and Column table.
Thanks for your support !
Alex
this is the code that a generate JTextArea and all data
private void popolaPianificazione(){
String tipo="Pianificazione";
String sql = "SELECT * FROM DomandePianificazione";
ResultSet res = null;
try {
res = MysqlStuff.richiediDatiSQL(sql);
if(res != null){
res.last();
if(res.getRow() != 0){
res.beforeFirst();
while(res.next()){
final String contatore = res.getString("id");
int conta = Integer.parseInt(contatore);
JPanel temp = new javax.swing.JPanel(new MigLayout("fill","grow"));
temp.setBorder(javax.swing.BorderFactory.createTitledBorder("DOMANDA "+"["+conta+"]"));
String domande = res.getString("Domanda");
domande.replace("รจ", "p");
javax.swing.border.Border border = BorderFactory.createEtchedBorder();
JTextArea domanda = new javax.swing.JTextArea(domande,2,2);
domanda.setBorder(border);
domanda.setBackground(colore);
domanda.setSize(400, 100);
domanda.setFont(font);
domanda.setMinimumSize(new Dimension(400,100));
domanda.setLineWrap(true);
domanda.setWrapStyleWord(true);
domanda.setOpaque(false);
domanda.setEditable(false);
JCheckBox rispostaC = new javax.swing.JCheckBox("Si/No");
JCheckBox rispostaCom = new javax.swing.JCheckBox("A completamento");
String rispostaCheck = res.getString("rispostaCheck");
String rispostaCompleta = res.getString("rispostaCompleta");
if (!"no".equals(rispostaCheck)){
rispostaC.setSelected(true);
}
else{
rispostaCom.setSelected(true);
}
JButton edit = new javax.swing.JButton("Modifica la domanda");
ButtonGroup buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup1.add(rispostaC);
buttonGroup1.add(rispostaCom);
rispostaC.setEnabled(false);
rispostaC.setRolloverEnabled(false);
rispostaCom.setEnabled(false);
rispostaCom.setRolloverEnabled(false);
temp.add(edit,"wrap");
edit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if ("Salva le modifiche".equals(edit.getLabel())){
System.out.println("Sto salvando...");
String pannello = "DomandePianificazione";
try {
SalvaDomanda(tipo,contatore,domanda,rispostaC,rispostaCom,pannello);
PanelPianificazione.revalidate();
PanelPianificazione.repaint();
} catch (SQLException ex) {
Logger.getLogger(ManageQuestionario.class.getName()).log(Level.SEVERE, null, ex);
}
SKIP
and this is the code for send data to mysql:
public static void inviaDatiSQL(String sql,String stat) throws SQLException, ClassNotFoundException{
UP = connetti();
System.out.println("INVIO dati a DB: \n"+ sql);
Statement stmt = null;
PreparedStatement test = UP.prepareStatement(sql);
test.setString(1, stat);
test.executeUpdate();
System.out.println("Finito !");
}

VSAM file locking when writing to it using Java JDBC

This is my first time trying to read and write to a VSAM file. What I did was:
Created a Map for the File using VSE Navigator
Added the Java beans VSE Connector library to my eclipse Java project
Use the code show below to Write and Read to the KSDS file.
Reading the file is not a problem but when I tried to write to the file it only works if I go on the mainframe and close the File before running my java program but it locks the file for like an hour. You cannot open the file on the mainframe or do anything to it.
Anybody can help with this problem. Is there a special setting that I need to set up for the file on the mainframe ? Why do you first need to close the file on CICS to be able to write to it ? And why does it locks the file after writing to it ?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.*;
public class testVSAM {
public static void main(String argv[]){
Integer test = Integer.valueOf(2893);
String vsamCatalog = "VSESP.USER.CATALOG";
String FlightCluster = "FLIGHT.ORDERING.FLIGHTS";
String FlightMapName = "FLIGHT.TEST2.MAP";
try{
String ipAddr = "10.1.1.1";
String userID = "USER1";
String password = "PASSWORD";
java.sql.Connection jdbcCon;
java.sql.Driver jdbcDriver = (java.sql.Driver) Class.forName(
"com.ibm.vse.jdbc.VsamJdbcDriver").newInstance();
// Build the URL to use to connect
String url = "jdbc:vsam:"+ipAddr;
// Assign properties for the driver
java.util.Properties prop = new java.util.Properties();
prop.put("port", test);
prop.put("user", userID);
prop.put("password", password);
// Connect to the driver
jdbcCon = DriverManager.getConnection(url,prop);
try {
java.sql.PreparedStatement pstmt = jdbcCon.prepareStatement(
"INSERT INTO "+vsamCatalog+"\\"+FlightCluster+"\\"+FlightMapName+
" (RS_SERIAL1,RS_SERIAL2,RS_QTY1,RS_QTY2,RS_UPDATE,RS_UPTIME,RS_EMPNO,RS_PRINTFLAG,"+
"RS_PART_S,RS_PART_IN_A_P,RS_FILLER)"+" VALUES(?,?,?,?,?,?,?,?,?,?,?)");
//pstmt.setString(1, "12345678901234567890123003");
pstmt.setString(1, "1234567890");
pstmt.setString(2,"1234567890123");
pstmt.setInt(3,00);
pstmt.setInt(4,003);
pstmt.setString(5,"151209");
pstmt.setString(6, "094435");
pstmt.setString(7,"09932");
pstmt.setString(8,"P");
pstmt.setString(9,"Y");
pstmt.setString(10,"Y");
pstmt.setString(11," ");
// Execute the query
int num = pstmt.executeUpdate();
System.out.println(num);
pstmt.close();
}
catch (SQLException t)
{
System.out.println(t.toString());
}
try
{
// Get a statement
java.sql.Statement stmt = jdbcCon.createStatement();
// Execute the query ...
java.sql.ResultSet rs = stmt.executeQuery(
"SELECT * FROM "+vsamCatalog+"\\"+FlightCluster+"\\"+FlightMapName);
while (rs.next())
{
System.out.println(rs.getString("RS_SERIAL1") + " " + rs.getString("RS_SERIAL2")+ " " + rs.getString("RS_UPTIME")+ " " + rs.getString("RS_UPDATE"));
}
rs.close();
stmt.close();
}
catch (SQLException t)
{
}
}
catch (Exception e)
{
// do something appropriate with the exception, *at least*:
e.printStackTrace();
}
}
}
Note: the OS is z/VSE
The short answer to your original question is that KSDS VSAM is not a DBMS.
As you have discovered, you can define the VSAM file such that you can update it both from batch and from CICS, but as #BillWoodger points out, you must serialize your updates yourself.
Another approach would be to do all updates from the CICS region, and have your Java application send a REST or SOAP or MQ message to CICS to request its updates. This does require there be a CICS program to catch the requests from the Java application and perform the updates.
The IBM Mainframe under z/VSE has different partitions that run different jobs. For example partition F7 CICS, partition F8 Batch Jobs, ETC.
When you define a new VSAM file you have to set the SHAREOPTIONS of the file. When I define the file I set the SHAREOPTIONS (2 3). 2 Means that only one partition can write to the file.
So when the batch program (in a different partition to the CICS partition) which is called from Java was trying to write to the file it was not able to write to the file unless I close the file in CICS first.
To fix it I REDEFINE the CICS file with SHAREOPTIONS (4 3). 4 Means that multiple partitions of the Mainframe can write to it. Fixing the problem
Below is a part of the definition code where you set the SHAREOPTION:
* $$ JOB JNM=DEFFI,CLASS=9,DISP=D,PRI=9
* $$ LST CLASS=X,DISP=H,PRI=2,REMOTE=0,USER=JAVI
// JOB DEFFI
// EXEC IDCAMS,SIZE=AUTO
DEFINE CLUSTER -
( -
NAME (FLIGHT.ORDERING.FLIGHTS) -
RECORDS (2000 1000) -
INDEXED -
KEYS (26 0) -
RECORDSIZE (128 128) -
SHAREOPTIONS (4 3) -
VOLUMES (SYSWKE) -
) -
.
.
.

run the java class from war file in tomcat server

i have uploaded one war file in remote tomcat server.here i have to unzip the war file.here i have to run the Demo java class on my browser.how can i do????
this is the saved path of Demo.java:
/var/lib/tomcat7/webapps/Example/WEB-INF/classes/com/testprops/ws
Here i have to run these means URL http://xx.xx.xx.xxx:8080/Example/ means am getting these page successfully.please check this:http://screencast.com/t/DKZW1t9Z1
This is my Demo.java:
public class Demo {
public String customerData(){
String customerInfo = "";
int a=10;
customerInfo = customerInfo + a;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/android","androiduser","AN124#7#7");
//Find customer information where the customer ID is maximum
PreparedStatement statement = con.prepareStatement("SELECT * FROM xcart_customers");
ResultSet result = statement.executeQuery();
while(result.next()){
customerInfo = customerInfo + a + "&" + result.getString("login") + "&" + result.getString("password") + "&"+result.getString("firstname") + "&"+result.getString("email");
//Here "&"s are added to the return string. This is help to split the string in Android application
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return customerInfo;
}
}
How can i run the Demo.java class on my browser.please help me.
That is because you need to write a servlet that runs the code. Basically when you give a request to the above given link, then it calls Demo.java class and the output is given.
It is recommended to please first learn a bit basics about servlets. That should help.
So have a simple servlet like
public void doGet(HttpServeletRequest r, HttpServletResponse s){
Demo demo = new Demo();
demo.run();//your Demo.java is invalid as all that try catch code needs to be inside a method
}

reading huge data from database and writing into xml Java

I have huge data billions of records in tables what is the best way to read it in plain Java and write it in XML file?
Thanks
If by best you mean fastest - I would consider using native database tools to dump the files as this will be way faster than using JDBC.
Java (+Hibernate?) will slow the process down unnecessarily. Easier to do sqlplus script and spool formatted fields into your xml file.
On Toad you can right click a table and click export to xml. on the commercial version I think you can export all tables but I'm not sure
Another possibility (working with all db with a JDBC driver) would be to use Apache Cocoon. There are actually two ways: XSP ((alone or and with ESQL). Both technos are really quick to develop.
XSP alone example. Think of XSP as a little bit like JSP but generating XML instead of HTML. From a DB for instance.
<?xml version="1.0"?>
<xsp:page language="java" xmlns:xsp="http://apache.org/xsp"
xmlns:esql="http://apache.org/cocoon/SQL/v2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://apache.org/cocoon/SQL/v2 xsd/esql.xsd"
space="strip">
<xsp:structure>
<xsp:include>java.sql.Connection</xsp:include>
<xsp:include>java.sql.DriverManager</xsp:include>
<xsp:include>java.sql.PreparedStatement</xsp:include>
<xsp:include>java.sql.SQLException</xsp:include>
<xsp:include>java.sql.ResultSet</xsp:include>
</xsp:structure>
<xsp:logic><![CDATA[
private static final String connectionString =
"jdbc:mysql://localhost/mandarin?user=mandarin&password=mandarin" ;
private Connection conn = null ;
private PreparedStatement pstmt = null ;
private void openDatabase() {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection (connectionString);
pstmt = conn.prepareStatement(
"select " +
" count(*) as cardinality " +
" from " +
" unihan50 u " +
" where " +
" unicode_id >= ? and " +
" unicode_id <= ? " ) ;
} catch (SQLException e) {
e.printStackTrace();
}
}
private int getRangeCardinality ( int lowerBound, int upperBound ) {
int cnt = 0 ;
try {
cnt = 2 ;
pstmt.setInt ( 1, lowerBound ) ;
pstmt.setInt ( 2, upperBound ) ;
boolean sts = pstmt.execute () ;
if ( sts ) {
ResultSet rs = pstmt.getResultSet();
if (rs != null && rs.next() ) {
cnt = rs.getInt ( "cardinality" ) ;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return cnt ;
}
private void closeDatabase() {
try {
pstmt.close () ;
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close () ;
} catch (SQLException e) {
e.printStackTrace();
}
}
]]>
</xsp:logic>
<ranges>
<xsp:logic><![CDATA[
openDatabase() ;
for ( int i = 0; i < 16 ; i++ ) {
int from = i * 0x1000 ;
int to = i * 0x1000 + 0x0fff ;
]]>
<range>
<from>0x<xsp:expr>Integer.toString(from, 16)</xsp:expr></from>
<to>0x<xsp:expr>Integer.toString(to, 16)</xsp:expr></to>
<count><xsp:expr>getRangeCardinality ( from, to )</xsp:expr></count>
</range>
}
closeDatabase () ;
</xsp:logic>
</ranges>
</xsp:page>
XSP is even more straightforward coupled with ESQL. Here is sample
<?xml version="1.0" encoding="UTF-8"?>
<xsp:page language="java" xmlns:xsp="http://apache.org/xsp"
xmlns:esql="http://apache.org/cocoon/SQL/v2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsp-request="http://apache.org/xsp/request/2.0"
xsi:schemaLocation="http://apache.org/cocoon/SQL/v2 xsd/esql.xsd"
space="strip">
<keys>
<esql:connection>
<esql:pool>mandarinMySQL</esql:pool>
<esql:execute-query>
<esql:query><![CDATA[
select
unicode_id,
kMandarin,
...
from
unihan50_unified
where
add_strokes = 0
order by
radical
]]>
</esql:query>
<esql:results>
<esql:row-results><key><esql:get-columns /></key></esql:row-results>
</esql:results>
</esql:execute-query>
</esql:connection>
</keys>
</xsp:page>
I'll be using database inbuild procedure (e.g. XML path) to get data already converted in xml format.
Now there are 2 ways to write in the file:
1. If you have to have Java interface (JDBC) to retrieve data (due to business req) then I'll simply read this data and write in a File (No XML Parser involvement unless you need to verify the output).
2. If you do not have Java restriction then I'll simply write a Stored Procedure which will dump XML data in a file.
Update to comment:
Workflow for fastest retrieval:
Create Stored Procedure which will retrieve data and dump into a file.
Call this SP through Java (as you said you need it)
Either SP can return you the file name or you can create SP which will take file name so you can dynamically manage the output location.
I have not used Oracle for a very long time but I hope this link can help you to kickstart.
If the DB is Oracle, then you can simply use JDBC with a SQLX query. This will generate your result set directly as XML fragments on the server much faster than if you'd do it on your own on the client side. SQLX has been available since 8.1.7 as project Aurora and since 9i in standard as XMLDB.
Here is a simple example.
select XMLelement ("Process",
XMLelement( "number", p.p_ka_id, '.', p_id ),
XMLElement( "name", p.p_name ),
XMLElement ( "processGroup", pg.pg_name ) )
from
PMP_processes p,
PMP_process_groups pg
where
condition ;
In addition to XMLelement, SQLX has XMLattribute, XMLforest, XMLaggregate... which allows you any resulting tree.
Use StAX to write the xml, not DOM.
You can query to the database and retrieve all data into a RESULTSET and use the following code to start off a root element.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element Element_root = document.createElement("rootElement");
Thereafter you can add on as many as child elements using
Element Element_childnode = document.createElement("childnode");//create child node
Element_childnode.appendChild(document.createTextNode("Enter the value of text here"));//add data to child node
Element_root.appendChild(Element_childnode);//close the child node
Do not forget to close the opened node close the root at the end WITHOUT FAIL
Use this to close root.
document.appendChild(Element_causelist);
At the end if you have a XSD validate it your xml against it.....googling the validation online will provide good results.... http://tools.decisionsoft.com/schemaValidate/
NOTE : TIME !!! It will take time when data is huge nos...
But I think this is one and the most easiest way of doing it....Taking in consideration the data, I think one should run the program during down time when there is less traffic....
Hope this helps....Good Luck Gauls....
public class someclassname{
public static String somemethodname(){
String sql;
sql="SELECT * from yourdatabase.yourtable ";
return sql;
}
public static String anothermethodname(){
/*this is another method which is used to excute another query simultaneously*/
String sql;
sql="SELECT * from youdatabase.yourtable2";
return sql;
}
private static void saveasxml(String sql,String targetFile) throws SQLException, XMLStreamException, IOException{
int i,count;
FileOutputStream fos;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://yourdomain:yourport/yourdatabase","username","password");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sql);
ResultSetMetaData rsmd=rs.getMetaData();
count=rsmd.getColumnCount();
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
fos=new FileOutputStream(targetFile);
XMLStreamWriter writer = outputFactory.createXMLStreamWriter(fos);
writer.writeStartDocument();
writer.writeCharacters("\n");
writer.writeStartElement("maintag line");
writer.writeCharacters("\n");
while(rs.next()){
writer.writeCharacters("\t");
writer.writeStartElement("foreveyrow-tagline");
writer.writeCharacters("\n\t");
for(i=1;i<count+1;i++){
writer.writeCharacters("\t");
writer.writeStartElement("Field"+i);
writer.writeCharacters(rs.getString(i));
writer.writeEndElement();
writer.writeCharacters("\n\t");
}
writer.writeEndElement();
writer.writeCharacters("\n");
}
writer.writeEndElement();
writer.writeEndDocument();
writer.close();
}catch(ClassNotFoundException | SQLException e){
}
}
public static void main(String args[]) throws Exception{
saveasxml(somemethodname(), " file location-path");
saveasxml(anothermethodname(), "file location path");
}
}
Thanks all for replying , so far i have managed to get a solution based on using threads and use multiple selects instead of one single complex sql joins (i hate SQL complex ones) life should be simple :) so i didn't waste too much time writing them i am using new threads for each select statements.
any better solution in POJO probabaly using spring is also fine
Thanks
gauls

Categories