Okay, fairly straightforward mysql insert from a form, the insert works fine but i wanted to have it check for duplicates first and kick out an error if the name already existed in the table.
That said, I worked out a few errors in the jsp, and have it down to an SQL syntax error. My confusion is that i prettymuch the same sql select statement working on another page, with a simple print out.
Here's my code:
<%@ page language="java" %>
<%@ page session ="true"%>
<%@ page import = "java.net.*" %>
<%@ page import = "java.util.*" %>
<%@ page import = "umtools.*" %>
<%@ page import = "java.sql.*" %>
<%@ include file = "globals.jsp" %>
<%@ page import = "javax.mail.*" %>
<%@ page import = "javax.mail.internet.*" %>
<%@ page import = "javax.activation.*" %>
<%
String user=(String)request.getSession().getAttribute("uid");
String chem_id=request.getParameter("cno");
String cas=request.getParameter("cas");
String id="";
String cn=request.getParameter("chem_name");
String formula=request.getParameter("formula");
String weight=request.getParameter("weight");
String iupac=request.getParameter("iupac");
String synonyms=request.getParameter("synonyms");
String structure=request.getParameter("cas");
PreparedStatement ps;
ResultSet rs;
ResultSet rs1;
ResultSet rs2;
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ncnpr", username, password);
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ncnpr", username, password);
Statement statement = connection.createStatement() ;
ResultSet resultset =
statement.executeQuery("select * from Chemicals where chem_name="+cn+"") ;
int ct = 0;
while(resultset.next())
{
ct++;
}
if (ct > 0)
{
throw new SQLException("Duplicate info<br>Chemical Name " + cn );
}
else
{
String qry1= "insert into Chemicals(chem_id, chemical_name, cas,formula,weight,iupac, synonyms, structure) values(?,?,?,?,?,?,?,?)";
ps = con.prepareStatement(qry1);
ps.setString(1, id);
ps.setString(2, cn);
ps.setString(3, cas);
ps.setString(4, formula);
ps.setString(5, weight);
ps.setString(6, iupac);
ps.setString(7, synonyms);
ps.setString(8, structure+".jpg");
ps.executeUpdate();
} }
catch(Exception e)
{
String errorMessage = "Exception caught : ";
out.println(errorMessage + e.toString());
return ;
}
finally
{
if (con != null)
{
con.close();
}
}
response.sendRedirect("new_chemical.jsp");
%>