Can i have more than one preparestatement in one .jsp file? I´m trying to execute this “jsp file”, but this code doesnt work for me.
Something like this:
<%
String login = request.getParameter("login");
String pwd = request.getParameter("password");
String name = request.getParameter("name");
Connection connection = null;
PreparedStatement pstatement = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
int updateQuery = 0;
if (login != null && password != null && full_name != null && ulevel != null && team_id != null) {
if (login != "" && password != "" && full_name != "" && ulevel != "" && team_id != "") {
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/<mydatabase>", "<mylogin>", "<mypwd>");
String queryString_1 = "INSERT INTO users (login,password) VALUES (?, ?)";
pstatement = connection.prepareStatement(queryString_1);
pstatement.setString(1, login);
pstatement.setString(2, password);
updateQuery = pstatement.executeUpdate();
String queryString_2 = "INSERT INTO members (name) VALUES (?)";
pstatement = connection.prepareStatement(queryString_2);
pstatement.setString(1, name);
updateQuery = pstatement.executeUpdate();
if(updateQuery_1 != 0 && updateQuery_2 != 0) {
response.sendRedirect("index.jsp");
}
} catch (Exception ex) {
out.println("Unable to connect to database.");
} finally {
pstatement.close();
connection.close();
}
}
}
%>
You may have as many
PreparedStatements as you need.To improve your code:
1. You must declare int updateQuery_1 = 0 and updateQuery_2 = 0.
2. You must use
updateQuery_1 = pstatement.executeUpdate();andupdateQuery_2 = pstatement.executeUpdate();on your two different sql statements.