SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy_HHmmSS");
String strCurrDate = formatter.format(new java.util.Date());
String strfileNm = "Customer_" + strCurrDate + ".txt";
String strFileGenLoc = strFileLocation + "/" + strfileNm;
String Query1="select '0'||to_char(sysdate,'YYYYMMDD')||'123456789' class_code from dual";
String Query2="select '0'||to_char(sysdate,'YYYYMMDD')||'123456789' class_code from dual";
String Query3="select param from dual";
try {
Statement stmt = null;
ResultSet rs = null;
Statement stmt1 = null;
ResultSet rs1 = null;
stmt = conn.createStatement();
stmt1 = conn.createStatement();
stmt2 = conn.createStatement();
rs = stmt.executeQuery(Query1);
rs1 = stmt1.executeQuery(Query2);
rs2 = stmt2.executeQuery(Query3);
File f = new File(strFileGenLoc);
OutputStream os = (OutputStream)new FileOutputStream(f,true);
String encoding = "UTF8";
OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
BufferedWriter bw = new BufferedWriter(osw);
while (rs.next() ) {
bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write(" ");
}
bw.flush();
bw.close();
} catch (Exception e) {
System.out.println(
"Exception occured while getting resultset by the query");
e.printStackTrace();
} finally {
try {
if (conn != null) {
System.out.println("Closing the connection" + conn);
conn.close();
}
} catch (SQLException e) {
System.out.println(
"Exception occured while closing the connection");
e.printStackTrace();
}
}
return objArrayListValue;
}
The above code is working fine. it writes the content of "rs" resultset data in text file
Now what i want is ,i need to append the
the content in "rs2" resultset to the "same text file"(ie . i need to append "rs2" content with "rs" content in the same text file)..
------------------edit part----------------
stmt = conn.createStatement();
stmt1 = conn.createStatement();
stmt2 = conn.createStatement();
rs = stmt.executeQuery(Query1);
rs1 = stmt1.executeQuery(Query2);
rs2 = stmt2.executeQuery(Query3);
while ( rs.next() ) {
while(rs1.next()){
while(rs2.next()){
bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write("\t");
bw.write(rs1.getString(1)==null? "":rs1.getString(1));
bw.write("\t");
bw.write(rs2.getString(1)==null? "":rs2.getString(1));
bw.write("\t");
bw.newLine();
}
}
}
Above code working fine.
My problem is
"rs" resultset contains one record in the table
"rs1" resultset contains 5 record in the table
"rs2" resultset contains 5 record in the table
"rs" data is getting recursive.
while writing to the same text file , the output i am getting like
1 2 3
1 12 21
1 23 25
1 10 5
1 8 54
but i need output like below
1 2 3
12 21
23 25
10 5
8 54
What things i need to change in my code.. Please advice
-----------------edit part1------------------
Expected Result is
1 2 3
1 12 21
1 23 25
1 10 5
1 8 54
but output i got like
1 2 3
12 21
23 25
10 5
8 54
new FileOutputStream(f,true);
You have already set the append flag to true(the second argument), so do the same as what you did with the previous result set.
See: http://java.sun.com/javase/6/docs/api/java/io/FileOutputStream.html
Related
2 problems, it outputs 1 2 3 4 3 5, instead of 1 2 3 4 5, which I'm not sure why followed by success but does not print out the data from the SQL table
Statement st = null;
ResultSet rs = null;
try {
System.out.println("1");
Connection con = DriverManager.getConnection(url, user, pass);
System.out.println("2");
//Class.forName(driver);
System.out.println("3");
st = con.createStatement();
rs = st.executeQuery("SELECT productcost " +
"FROM producttable " +
"WHERE productid = 3;");
System.out.println("4");
if (rs.next()) { //get first result
System.out.println(rs.getInt(1)); //coloumn 1
}
System.out.println("5");
System.out.println("Success");
} catch (Exception e) {
System.out.println("Error");
}
The reason you are seeing 3 in-between 4 and 5 is because the ResultSet contains 3.
ResultSet.getInt
Retrieves the value of the designated column in the current row of
this ResultSet object as an int
Try debugging your code and stepping through that section. You'll see what I am displaying below.
You must have '3' as a data in first column! Cause your printing the data of first column of record.i don't see any problem here!
I'm trying to execute a query in database in MySQL using PreparedStatement and ResultSet.
The problem is that I am getting an empty result set in MySQL, otherwise I get a correct result on Derby.
Connection con= null;
ResultSet reslt =null;
PreparedStatement ps = null;
try
{
//Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/SAIID","SAIID","SAIID");
//con = DriverManager.getConnection("jdbc:derby://localhost:1527/pavillons","saiid","saiid");
String Query =" SELECT * FROM ETUDIANT_PAV WHERE PAVILLONS = ? AND CHAMBRE = ? "
ps = con.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ps.setString(1, "A");
ps.setString(2, "1");
reslt = ps.executeQuery();
//String thequeryresult= reslt.getString("NOM_PRENOM");
//System.out.println ("this is the query result"+thequeryresult);
JOptionPane.showMessageDialog(null, "Query Executed");
//con.close();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
Seeing this lines :
reslt = ps.executeQuery();
//String thequeryresult= reslt.getString("NOM_PRENOM");
If you used that commented line to checked the result, this can't worked. You need to move the cursor of that result set to the first line (start to -1).
For that, use ResultSet.next() that will return true until there is no more row to read.
reslt = ps.executeQuery();
while(reslt.next()){ //read all lines
System.out.println(reslt.getString("NOM_PRENOM"));
}
String selctedItemPAV = indextostring(jComboBox1.getSelectedIndex());
String selctedItemCH = jList1.getSelectedValue();
String Query =" SELECT * FROM etudiant_pav WHERE PAVILLONS = ? AND CHAMBRE = ? " ;
rst = theSelectQuery(Query,selctedItemPAV ,selctedItemCH); //this is the posted function
DefaultListModel listModel = new DefaultListModel();
jList3.setModel(listModel);
System.out.println (selctedItemCH + " doppppppppp " +selctedItemPAV + jComboBox1.getSelectedIndex());
System.out.println ("doppppppppp222222222");
if (rst.isBeforeFirst())
{
System.out.println ("ttttttttttttttttttttttttttttttttttttttttttttt"); //the excution stops here in application.....
jList3.setEnabled(true);
listModel.clear();
jLabel1.setVisible(false);
while (rst.next())
{
String aff="hhh";
aff= rst.getString("NOM_PRENOM");
System.out.println ("dooooooooo"+aff);
listModel.addElement(aff);
}
}
else
{
jLabel1.setVisible(false);
jList3.setEnabled(false);
JOptionPane.showMessageDialog(null, "la chambre est vide ");
}
rst.close();
}
catch (Exception ex){
}
Basically I have Column row with the value of:
ID Title
----- ----------------------------------
| 1 |ماهر زين - عليك صلى الله (Official) |
----- ----------------------------------
-
String Title = null;
DBConnect Database = new DBConnect();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
con = Database.getcon();
String query2="SELECT TITLE FROM table WHERE ID=?";
ps = con.prepareStatement(query2);
ps.setInt(1, 1);
rs=ps.executeQuery();
if(rs.next()){
Title=rs.getString(1);
System.out.println(Title);
}
} finally {
if(ps != null)
ps.close();
if(rs != null)
rs.close();
if(con != null)
con.close();
}
To connect to the DB I Do:
public DBConnect(){
try{
Class.forName("com.mysql.jdbc.Driver");
String unicode="useSSL=false&useUnicode=yes&characterEncoding=UTF-8";
con = DriverManager.getConnection("jdbc:mysql://localhost:15501/db?"+unicode, "root", "pwd");
st = con.createStatement();
}catch(Exception ex){
System.out.println(ex.getMessage());
System.out.println("couldn't connect!");
}
}
But the Output I get is: ????? ??? ????? ? ??? ?? ????? (Official)
I also have tried:
ALTER DATABASE <name> CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
-
I also tried:
select
c.character_set_name
from information_schema.tables as t,
information_schema.collation_character_set_applicability as c
where c.collation_name = t.table_collation
and t.table_schema = "duckdb"
and t.table_name = "stackscontents";
The output I get is `utf8mb4
FYI: My my.ini file says default-character-set=utf8
Yet still i'm getting the output as: ????? ??? ????? ? ??? ?? ????? (Official)
All replies are much appreciated
CallableStatement stmt = null;
String sql = "begin ? := TEST.USER_LIST.queryByUser(?,?,?,?); end;";
ResultSet rs = null;
try {
stmt = conn.prepareCall(sql);
stmt.registerOutParameter(1, OracleTypes.CURSOR);
stmt.setString(2, "user1"); stmt.setInt(3, 1); // offset
stmt.setString(4, "Update_Date"); stmt.setString(5, "DESC");
stmt.execute();
if(stmt.getObject(1)==null) {
System.out.println("Null value");
} else {
rs = (ResultSet) stmt.getObject(1);
int i = 0;
while (rs.next()) { i++; }
System.out.println("rs size: " +i);
stmt.close();
rs.close();
}
} catch (Exception ex) {
} finally {
try { rs.close(); stmt.close();
} catch (Exception ex) {}
}
OUTPUT:
rs size: 19
PROBLEM: Total rows return by this code is 10 less than rows in db
if 50 rows in db it shows 40, if 30 it shows 20, if 9 its shows 0.
You need one of ResultSet (rs) types: ResultSet.TYPE_SCROLL_INSENSITIVE
or ResultSet.TYPE_SCROLL_SENSITIVE for that to work
Usually you count the ResultSet starting from rs.beforeFirst() so you count the first element to.
int size = 0 ;
if (rs != null){
rs.beforeFirst();
rs.last();
size = rs.getRow();
}
My suggestion is to make a SELECT COUNT(*) inside the stored procedure
Found the problem, it was ojdbc jar issue, was using ojdbc6, now have replaced with ojdbc14. after jar change it is working fine, Thanks all for reply.
I want to use two sql query in my java code. the first query retain all row of table2 and the second one get it's rows one by one. I wrote follow code but it face to "This ResultSet is closed, it means rs ResultSet " error. How can I fix?
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
ResultSet rsWithin = stmt.executeQuery(sqlWithin);
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}
You need to create separate PreparedStatement object for inner query
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
PreparedStatement preparedStatement = null;
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
preparedStatement = dbConnection.prepareStatement(sqlWithin);
ResultSet rsWithin = preparedStatement.executeQuery();
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}