Re: Java / JSP / MySQL
On Jan 17, 3:37 pm, kuukele...@gmail.com wrote:
I got it partly to work using this great tutorial, but I'm not able to
do insert querys yet, select and update querys are working fine but
with insert querys I get an exception:
org.apache.jasper.JasperException: Exception in JSP: /index.jsp:21
18: db.connect();
19:
20: try {
21: i = db.insert("INSERT INTO `sessions` (`ip`) VALUES
('127.0.0.1')");
22: out.println(i);
23: }
Java Class:
public int insert(String sql) throws SQLException {
Statement s = con.createStatement();
int res = s.executeUpdate(sql);
return (res == 0) ? null : res;
}
public int update(String sql) throws SQLException {
Statement s = con.createStatement();
int res = s.executeUpdate(sql);
return (res == 0) ? null : res;
}
Again, the update query works but the insert is not working :s
http://www.roseindia.net/jsp/usingbeansinjsp.shtml
Why don't you write a plain Java class that handles all the database
interaction? Call the relevant method when required in the JSP(Though
IMO thats a bad design, better way would be to use Servlets to handle
such actions). Something like this
// import relevant classes
public class DatabaseManager {
private Resultset rs = null;
public DatabaseManager(){ connect(); //establish connection when
creating object }
public void connect(){ // implementation for database connection }
public void insert(){ // implementation for insert in to table }
public void otherMethods(){ // provide other methods which involve
database interaction }
public String [] myTableList(){ // provide implementation for
populating items from mytable
ArrayList list = new ArrayList();
while (rs.next())
list.add(rs.getString(1));
}
}
Your original JSP code would be reduced to
<%@ page import="DatabaseManager" %>
<%
// Perform all the operations needed using DatabaseManager class
DatabaseManager dm = new DatabaseManager();
//Iterate over dm.myTableList()
%>
I have not written the implementation as you already know how to
connect to database and what query to be executed.
Note that this approach is a bad way of solving big application. BTW I
did not quite understand what you mean by
the next stap for me was finding a logical way of
creating a database connection for a Wizard Application
Can you explain that a bit more?
--
Ck
http://www.gfour.net