private void btn_nextActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect =DriverManager.getConnection("jdbc:odbc:reimbursement");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
try
{
stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
sql = "select * from reimbursementMaster";
rs = stmt.executeQuery( sql );
rs=stmt.getResultSet();
if(rs.next())
{
empcode=rs.getString("EmployeeCode");
empname=rs.getString("EmployeeName");
loc=rs.getString("Location");
location=loc;
}
else
{
rs.previous();
JOptionPane.showMessageDialog(this, "End of File","Message",JOptionPane.INFORMATION_MESSAGE );
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
Let me guess...
Your problem is you are getting only the first result all the times is because the resultset is reopened from scratch every time you press the next button.
declare Resultset rs as class member,
open rs out of btn_nextActionPerformed() (where you build the UI
can be a good place) and rs.next() should work as expected.
Related
How to Close Statements and Connection in This Method
public static ResultSet getData (String query){
try {
Connection con = ConnectionProvider.connect();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
System.out.println(e);
return null;
}
You need to close connections in finally block:
try {
...
}
catch {
...
}
finally {
try { st.close(); } catch (Exception e) { /* Ignored */ }
try { con.close(); } catch (Exception e) { /* Ignored */ }
}
In Java 7 and higher you can define all your connections and statements as a part of try block:
try(Connection con = ConnectionProvider.connect();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
) {
// Statements
}
catch(....){}
One should use try-with-resources to automatically close all.
Then there is the p
public static void processData (String query, Consumer<ResultSet> processor){
try (Connection con = ConnectionProvider.connect();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
processor.accept(rs);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
System.getLogger(getClass().getName()).log(Level.Error, e);
}
}
processData("SELECT * FROM USERS", rs -> System.out.println(rs.getString("NAME")));
Or
public static <T> List<T> getData (String query, UnaryOperator<ResultSet, T> convert){
try (Connection con = ConnectionProvider.connect();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
List<T> result = new ArrayList<>();
while (rs.next()) {
result.add(convert.apply(rs));
}
return result;
} catch (SQLException e) {
System.getLogger(getClass().getName()).log(Level.Error, e);
throw new IllegalArgumentException("Error in " + query, e);
}
}
Then there is the danger with this function, that users will compose query strings like:
String query = "SELECT * FROM USERS WHERE NAME = '" + name + "'";
Which does not escape the apostrophes like in d'Alembert. It opens the gates to SQL injection, a large security breach. One needs a PreparedStatement, and then can use type-safe parameters.
As with try-with-resources the code already is reduced (no explicit closes), you should drop this kind of function. But almost most programmers make this mistake.
I am getting this error when I run my code
Below is the code I have used:
String sql="SELECT * FROM PERSONS WHERE PERSONJOB='ADMIN'";
Statement stmt=null;
ResultSet rs=null;
try
{
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
While(rs.next())
{
String name=rs.getString(1);
long id=rs.getLong(2);
System.out.println(name);
System.out.println(id);
}
}
catch(Exception e)
{
throw e;
}
finally
{
rs.close();
stmt.close();
}
I want to reuse the connection, so I didn't close the connection.
After I closed the ResultSet and Statement, I am getting the "maximum open cursors exceeded" error.
Anyone please help me to solve this error.
My guess is that the close() of your ResultSet is failing, which would result in multiple open cursors and eventually hit the max configured open cursor count. Could you modify your code to:
Statement stmt = conn.createStatement();
try
{
ResultSet rs = stmt.executeQuery("SELECT * FROM PERSONS WHERE PERSONJOB = 'ADMIN'");
try
{
while ( rs.next() )
{
String name = rs.getString(1);
long id = rs.getLong(2);
System.out.println(name);
System.out.println(id);
}
}
finally
{
try
{
rs.close();
}
catch (Exception ignore) { }
}
}
finally
{
try
{
stmt.close();
}
catch (Exception ignore) { }
}
EDIT: will be good to also clean up the already opened cursors with a combination of:
SELECT oc.user_name, oc.sql_text, s.SID, s.SERIAL#
FROM v$open_cursor oc
, v$session s
WHERE oc.sid = s.sid
EXEC SYS.KILL_SESSION(xxx,xxxxx);
or restart the DB.
when i wrote function instead of procedure, it compiled.
CREATE OR REPLACE function ilce_gtr
(
p_ilkodu number
)
RETURN VARCHAR2 AS
p_geridonen varchar2(1000);
begin
for rec in(SELECT ADI FROM ILCE WHERE Y_IL=p_ilkodu)
loop
p_geridonen := p_geridonen || '|' || rec.ADI;
end loop;
return p_geridonen;
end;
/
then i created xml via web method, it was successful.
#WebMethod
public String get_ilce (int p_ilkodu) {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
String deger=null;
try {
conn= getConnection_test();
String query = "SELECT ILCE_GTR('" + p_ilkodu + "') FROM DUAL";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
deger = rs.getString(1);
}
} catch (Exception e) {
return "hata";
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
return "hata";
}
}
return deger;
}
I want to do the same for inserting to database, can u help me?
#WebMethod
public String add_ilce (int yourInput) {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
String deger=null;
try {
conn= getConnection_test();
String query = "INSERT INTO DUAL" + "(yourAttributeName)" +"VALUES (?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, yourInput);
preparedStmt.execute();
} catch (Exception e) {
return "hata";
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
return "hata";
}
}
return deger;
}
EDIT: I suggest you to use DAO approach for such scenarios, check here: Data access object (DAO) in Java
EDIT: I edited the post now it must work as it should be, sorry I had some mistakes
web service didnt appear on localhost, there are others.
#WebMethod
public String add_ilce (String p_no, int p_tplm) {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
String deger=null;
try {
conn= getConnection_test();
String query = "INSERT INTO DUAL" + "TEMP_TAHAKKUK_AG(ABONENO,TOPLAM)" +"VALUES ('p_no','p_tplm')";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
deger = rs.getString(1);
}
} catch (Exception e) {
return "hata";
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
return "hata";
}
}
return deger;
}
What I did wrong? I tried to swap rs.close(), pstmt.close(), conn.close().
I created a PreparedStatement.
But I still can not display the contents of a database table. If I remove conn.close(), everything works! How close the connection and get an output on the jsp?
This is my code:
public ResultSet executeFetchQuery(String sql) {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = Database.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(PhoneDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
return rs;
}
public ArrayList<Phone> getAllPhone() {
ArrayList<Phone> list = new ArrayList<>();
String sql = "SELECT * FROM phones.product;";
ResultSet rs = executeFetchQuery(sql);
try {
while (rs.next()) {
Phone phone = new Phone();
phone.setId(rs.getInt("id"));
phone.setName(rs.getString("name"));
phone.setPrice(rs.getInt("price"));
phone.setQuantity(rs.getInt("quantity"));
phone.setDescription(rs.getString("description"));
System.err.println(phone);
list.add(phone);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
return list;
}
ResultSet rs = executeFetchQuery(sql);
The above statement closes everything.
Actually your code should be
DBConnection
Iterate through result set
Store the values/display the value directly(depends on your need)
Finally close the connection.
Which is the proper way to access the data from db.
The more common pattern for this kind of process is to maintain the connection and the statement outside the main query code. This is priomarily because connections would generally be allocated from a pool as they are expensive to create and preparing the same statement more than once is wasteful.
Something like this is most likely to work both efficiently and correctly.
static final Connection conn = Database.getConnection();
static final String sql = "SELECT * FROM phones.product;";
static final PreparedStatement pstmt = conn.prepareStatement(sql);
public ArrayList<Phone> getAllPhone() {
ArrayList<Phone> list = new ArrayList<>();
ResultSet rs = pstmt.executeQuery();
try {
while (rs.next()) {
Phone phone = new Phone();
phone.setId(rs.getInt("id"));
phone.setName(rs.getString("name"));
phone.setPrice(rs.getInt("price"));
phone.setQuantity(rs.getInt("quantity"));
phone.setDescription(rs.getString("description"));
System.err.println(phone);
list.add(phone);
}
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
rs.close();
}
return list;
}
Note how the ResultSet is closed in a finally block to stop leaks.
There are variations of this pattern which, for example, only create the connection and prepare the statement at the last minute rather than as static final fields like I have here.
When i run my website it on glassfish server everything works fine but after some time its stop responding and I need to restart glassfish.. I think its cause I not closing the connection. Can someone tell me if this is the problem? if yes how to close it? Here is one of my function.
public Album get_album (String title)
{
try{
//creates a connection to the server
Connection cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
PreparedStatement pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
ResultSet rs = pst.executeQuery();
if(rs.next()) {
Album a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
return a;
}
}
catch (Exception e) {
String msg = e.getMessage();
}
return null;
}
Assumming the unique error in your application is for not closing the resources after using them, your code should change to:
public Album get_album (String title) {
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Album a = null;
try{
//creates a connection to the server
cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
rs = pst.executeQuery();
if (rs.next()) {
a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
//don't return inside try/catch
//return a;
}
} catch (Exception e) {
String msg = e.getMessage();
//handle your exceptions
//e.g. show them in a logger at least
e.printStacktrace(); //this is not the best way
//this will do it if you have configured a logger for your app
//logger.error("Error when retrieving album.", e);
} finally {
closeResultSet(rs);
closeStatement(pst);
closeConnection(cn);
}
return a;
}
public void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeStatement(Statement st) {
if (st!= null) {
try {
st.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeResultSet(ResultSet rs) {
if (rs!= null) {
try {
rs.close();
} catch (SQLException e) {
//handle the exception...
}
}
}