One Statement st = conexion.createStatement();
is sufficient. Don't keep recreating the statement. You only have a limited amount of times you can call createStatement. If you need a nested query, make two statements, st and st2, but do not keep calling createStatement for the same variable.
Also, if you are going to use connections in scriptlets, you should at the very least make a class to put the actual connecting part in, i.e. Class.forName("org.gjt.mm.mysql.Driver"); Connection conexion = DriverManager.getConnection(....);
and then just call that in the JSP. That way you don't have messy connection code in every JSP and when you have to change the server IP or username or something you won't have to go change a slew of JSPs.
And don't open the connection 10 times in one JSP. You wouldn't even want to do that in a Servlet. You would want to create a member variable that is of type Connection
, open it, and keep it open and until the end.
If you are going to use scriptlets, your code should be at least this clean:
<%
//call a static method in a class you create to get the connection
Connection connection = Appname.dbclass.getConnection();
if(connection==null)
{
out.print("error connecting");
return;
}
Statement st = connection.createStatement();
ResultSet rs = null;
...
//do all your stuff
...
if(rs!=null)
{
try
{
rs.close();
}
catch(Exception ex){}
}
if(st!=null)
{
try
{
st.close();
}
catch(Exception ex){}
}
if(connection!=null)
{
try
{
connection.close();
}
catch(Exception ex){}
}
%>
Also, instead of doing "select * from table" followed by something like:
while (rs.next()){
aaa = rs.getObject("aaa").toString();
}
use a WHERE CLAUSE in your SQL to limit the number of rows returned to ONE, and also limit the fields you pull to the ones you need ("select aaa from table WHERE id=1") and then an if-statement:
if (rs.next()){
aaa = rs.getObject("aaa").toString();
}
With your present code, each time you go through the loop again, aaa is being overwritten with a new value. Its wasting a ton of processing time either doing nothing or ensuring that the result is completely wrong.