MySQL query returns empty resultset - java

Currently I'm writing a very simple Java Servlet which will only execute one query and print the results.
The issue I'm facing is that it's working locally using JBoss as AS. When I deploy it to TomCat remotely, the same query is returning no results.
My observations:
The table has data. I've used SQuirrelSQL to check (about 100 rows);
Using the mysql cli it is also returning no results;
The code below returns "yes yes yes yes..." locally, but remotely only "go"
The code:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setHeader("Content-Type", "application/json");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace(res.getWriter());
}
List<Opportunity> opportunityList = new ArrayList<Opportunity>();
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/dbname", "dbuser", "dbpwd");
st = conn.createStatement();
rs = st.executeQuery(QUERY);
while(rs.next()) {
res.getWriter().print("yes ");
opportunityList.add(new Opportunity(rs));
}
} catch (SQLException e) {
opportunityList.clear();
res.getWriter().print("nooo ");
res.getWriter().println(e.toString());
} finally {
try {
res.getWriter().write("go ");
conn.close();
st.close();
rs.close();
} catch (Exception e) {
res.getWriter().write("noooo2");
res.getWriter().println(e.toString());
}
}
res.getWriter().write(new Gson().toJson(opportunityList));
}
EDIT-- The query:
SELECT o.ID, o.NAME, s.DESCRIPTION, pt.NAME, o.START_DATE, so.OWNER,
FROM SCOUT_OPPORTUNITY so
INNER JOIN OPPORTUNITY o ON so.OPPORTUNITY_ID = o.ID
INNER JOIN STATUS_DESC s ON s.NAME = o.STATUS_NAME
LEFT JOIN PROJECT_TYPE pt ON pt.ID = o.PROJECT_TYPE_ID
ORDER BY o.ID

Related

java.sql.SQLException:ORA -01000:maximum open cursors exceeded in JAVA

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.

Inconsistencies with mySQL delete query

I've encountered an some inconsistencies regarding the results from an SQL query.
Here is the query which I'm using as a prepared statement.
delete ROLE_USER_MAP
from ROLE_USER_MAP inner join ROLE_MANAGER on ROLE_USER_MAP.R_ID=ROLE_MANAGER.R_ID
where ROLE_USER_MAP.U_ID= ? and ROLE_MANAGER.M_ID= ?
Here is how I calling the prepared statement in my Java application.
public void deleteRoles(String mID, String uID) throws OperationFailedException
{
Connection conn = null;
try
{
conn = this.getConnection();
this.deleteRoles(mID, uID, conn);
}
catch (Exception e)
{
AdminLogger.error(this.getClass(), e);
throw new OperationFailedException("Failed to remove roles for user.");
}
finally
{
try
{
conn.close();
}
catch (Exception e)
{
}
}
}
private void deleteRoles(String mID, String uID, Connection conn) throws SQLException
{
PreparedStatement stmt = null;
try
{
stmt = *retrieving ps*
stmt.setString(1, uID);
stmt.setString(2, mID);
int i = stmt.executeUpdate(); // returns 1 here
if (i < 1)
{
throw new SQLException("Failed to remove roles for user.");
}
} finally
{
stmt.close();
}
}
It runs fine locally and in SSMS with all rows fitting the where clause being deleted but when I try to deploy it to my hosted server, only the first row in the table is being deleted.
Can anyone help me with this?
Thanks in advance.

Trying to show info from database into terminal

I'm trying to display a list of the names of people in the database from the terminal, but not sure about how I would go about this. Right now I'm using a prepared statement
public static void showNames() throws SQLException {
Statement stmt=null;
Connection conn=null;
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String selectTable="SELECT * FROM userInfo;";
stmt.execute(selectTable);
}
You're close.
Below code is not a complete answer, but hopefully enough to get you moving in the direction of obtaining a complete answer. The below code is basically the code you posted with some modifications.
public static void showNames() throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
String selectTable="SELECT * FROM userInfo;";
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
rs = stmt.executeQuery(selectTable);
while (rs.next()) {
Object obj = rs.getObject("name of column in database table USERINFO");
System.out.println(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}
You didn't post the structure of database table USERINFO, so replace name of column in database table with the actual column name.
By the way, there are many examples of how to do this on the Internet, for example Processing SQL Statements with JDBC.

How to delete data from database using JDBC

I am trying to make a form where sellers can insert new items, new category and delete items. Now I have problem with DELETE.
This is my code and if somebody know how to fix it please help.
String id = "42";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/projekat","root","");
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ? ;");
prepared_statement.setString(1, id);
int result_set = prepared_statement.executeUpdate();
if (result_set > 0)
{
System.out.println("Deleted");
}
else
{
System.out.println("Can't delete");
}
} catch (Exception ex) {
System.out.println(ex);
}
Try this:
String id = request.getParameter("id");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/projekat","root","");
PreparedStatement prepared_statement = null;
String strQuery = "DELETE FROM artikli WHERE id= ?";
prepared_statement = connection.prepareStatement(strQuery);
prepared_statement.setString(1, id);
int result_set = prepared_statement.executeUpdate();
if (result_set > 0)
{
// System.out.println(result_set);
response.sendRedirect("Prodaja2.jsp");
}
else
{
// System.out.println(result_set);
response.sendRedirect("Prodaja2.jsp?error=Can'tDelete");
}
} catch (Exception ex) {
out.print(ex);
} finally {
try {
stmtProd.close();
connection.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
In your code the semicolon after the query may be conflicting. And also don't forget to close the connections in the finally block created because it may lead to resource leak and connection will remain active even if the user logs out.
One error is here, that is in your syntax
Change the code
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ? ;");
to
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ?");
If there is no other errors, Check value in id, there is a chance of null value.

Java Servlet DB Query with Ajax - slow query time and querystring not always fully passed to the servlet

I'm trying to create a AJAX based SQL query with Java EE and Servlets. I'm using Glassfish 3.01 and MS SQL server with Jquery on the client side.
I put everything together, and bind my ajax function to the textfield's onkeyup event. But sometimes When I put 'teststring' into the textbox only "teststrin" passed to the Servlet. So basically the last char disappears and therefore the query result is not correct.
Not to mention when the resultset contains large amount of data the query is pretty slow. Could you please check if I'm doing something wrong on the server and client side?
On the client side I have this JQuery function:
function ajaxSearch(sstring) {
if (sstring.length < 3)
{
$("#external").html("at least 3 chars please....")
}
else
{
$('#loading').ajaxStart(function() {
$(this).show()
$("#external").hide()
});
$('#loading').ajaxComplete(function() {
$(this).hide()
$("#external").show()
});
$.ajax({
type:"GET",
url: "/myApp/getStd",
dataType: "application/x-www-form-urlencoded",
data: "sstring="+escape(sstring),
async: true,
success: function(data){
$("#external").html(data);
}
})
}
}
On the server side I have this:
#WebServlet(name="getStd", urlPatterns={"/getStd"})
public class getStd extends HttpServlet {
#Override
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList rows = new ArrayList();
res.setCharacterEncoding("UTF-8");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String sql=null;
String test= req.getParameter("sstring");
try{
InitialContext cxt = new InitialContext();
if (cxt == null) {
throw new Exception("Uh oh -- no context!");}
DataSource ds = (DataSource) cxt.lookup( "jdbc/Sample" );
conn = ds.getConnection();
stmt = conn.createStatement();
sql="Select * from MYDB.dbo.testdb where myField like '%"+req.getParameter("sstring")+"%';";
rs = stmt.executeQuery(sql);
while(rs.next()){
stdRecord cols = new stdRecord();
cols.setTeljel(rs.getString("Field1"));
cols.setTitle(rs.getString("Field2"));
cols.setICS(rs.getString("Field3"));
cols.setREF(rs.getString("Field4"));
rows.add(cols);
}
req.setAttribute("std", rows);
req.setAttribute("query",test );
req.getRequestDispatcher("/showRes.jsp").forward(req, res);
// close everything to free up resources
rs.close();
rs = null;
stmt.close();
stmt = null;
conn.close(); /
conn = null;
rows=null;
} catch (SQLException e) {
e.printStackTrace(out);
} catch (Exception e) {
e.printStackTrace(out);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) { ; }
rs = null;
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
}
}
}
Thanks in advance.
As to the lag in keyup, I think this is related to the performance issue, so let's fix that first and then review afterwards.
As to the performance, you've given very little information about your setup, but two common solutions which are often overlooked by starters are the following:
Use a connection pooled DataSource instead of DriverManager. This saves the cost of connecting the DB on every query (which can take over 200ms while a pooled connection is returned in no-time). Consult the JNDI resource config documentation of the application server in question for details (hint: admin console).
Limit the resultset size in SQL side instead of in Java side. This saves the cost of transferring irrelevant data over network. Just return the top 10 results or something instead of the entire table. Consult the SQL manual of the database in question for details (hint: SET ROWCOUNT).

Categories