0

If I have a code with interface that takes data from user then stores this data in variables of type string, how can I insert this variable in a database? Here is an example of what I say :

String s1="user@hotmail.com";
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con=
 DriverManager.getConnection("jdbc:derby://localhost:1527/SampleDB","app","app");
Statement st=con.createStatement();
st.executeUpdate("INSERT INTO EMAIL"+"(ID)"+"VALUES(s1)");

But this way is not working and doesn't insert this variable of type string in database!

How can I do this?

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 1
    Your first problem is that you aren't concatenating your variable, the name is part of the actual string. Your second problem is that you're concatenating user-supplied input directly into your SQL, instead of using prepared statements - this leaves you open to SQL Injection, so don't do that. – Clockwork-Muse Apr 27 '12 at 21:08

1 Answers1

1

Use PreparedStatemt. You can find an example in http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

To prevent SQL injection all queries should be parametrized and String concatenation should never be used to create dynamic SQL.

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148