Pregunta

I'm writing a webpage that takes input from a form, sends it through cgi to a java file, inserts the input into a database through sql and then prints out the database. I'm having trouble inserting into the database using variables though, and I was wondering if anyone would be able to help me out.

String a1Insert = (String)form.get("a1");
 String a2Insert = (String)form.get("a2");

This is where I get my variables form the form (just believe that it works, there's a bunch more back end but I've used this before and I know it's getting the variables correctly).

 String dbURL = "jdbc:derby://blah.blahblah.ca:CSE2014;user=blah;password=blarg";
  Connection conn = DriverManager.getConnection(dbURL);
  Statement stmt = conn.createStatement();
  stmt.executeUpdate("set schema course");
 stmt.executeUpdate("INSERT INTO MEMBER VALUES (a1Insert, a2Insert)"); 
 stmt.close();

This is where I try to insert into the databse. It give me the error:

Column 'A1INSERT' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'A1INSERT' is not a column in the target table.

If anyone has any ideas that would be lovely ^.^ Thanks

¿Fue útil?

Solución

java.sql.Statement doesn't support parameters, switching to java.sql.PreparedStatement will allow you to set parameters. Replace the parameter names in your SQL with ?, and call the setter methods on the prepared statement to assign a value to each parameter. This will look something like

String sql = "INSERT INTO MEMBER VALUES (?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "a1");
stmt.setString(2, "a2");
stmt.executeUpdate();

That will execute the SQL

INSERT INTO MEMBER VALUES ('a1', 'a2')

Notice the parameter indexes start from 1, not 0. Also notice I didn't have to put quotes on the strings, the PreparedStatement did it for me.

Alternatively you could keep using Statement and create your SQL string in Java code, but that introduces the possibility of SQL injection attacks. Using PreparedStatement to set parameters avoids that issue by taking care of handling quotes for you; if it finds a quote in the parameter value it will escape it, so that it will not affect the SQL statement it is included in.

Oracle has a tutorial here.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top