Smith Pual
Smith Pual

Reputation: 1

JDBC insert Statement not working

I am trying to create a java application that insert data in a database. Application is fairly simple. It take 3 input from user and insert that input to database. Everything working but I get sql error executing insert statement. Here is code snippet.

sa.executeUpdate("INSERT INTO history (to, subject, body)"+"VALUES("+ DATA1 + "','" + DATA2 + "','" +DATA3+ "')'");

I am sure I am having problem with the Double Quotes and Single Quotes in statement.

Upvotes: 0

Views: 4812

Answers (4)

Girish Acharya
Girish Acharya

Reputation: 115

1.Rather than using String Class use String Buffer or String Builder which is a mutable class. On the other hand, String Class is immutable. You can use String Buffer like

  1. String Buffer stbuffer = new String Buffer();

    stbuffer.append("insert into ");
    stbuffer.append("<tablename> ");
    stbuffer.append("<fields >");
    stbuffer.append(" values");
    stbuffer.append("(+");
    stbuffer.append(String);
    stbuffer.append(")");  ....etc
    
  2. You can get the final string representation using stbufffer.toString();

  3. You can insert this type of queries to exceute update() methods like ins.executeUpdate(stbuffer.toString);

  4. You can also use it like this for Insert statement and also for Prepared Statement

Upvotes: -1

Jayesh
Jayesh

Reputation: 6111

As Vinesh Suggested the solution, I would simply like to tell, better you take one variable as

String query="SQL QUERY";
then just do System.out.println(query);

then run the line,

PreparedStatement statement = connection.prepareStatement(query)

so that, you will correctly identify the final query formed.

Upvotes: 0

Cameron Skinner
Cameron Skinner

Reputation: 54276

You should always use PreparedStatements for this kind of thing. It takes care of quoting for you and protects you from SQL injection attacks:

PreparedStatement statement = connection.prepareStatement("INSERT INTO history (to, subject, body) VALUES (?, ?, ?)");
statement.setString(1, DATA1);
statement.setString(2, DATA2);
statement.setString(3, DATA3);
statement.execute();

Not only that, but the database driver can compile and cache prepared statements, potentially making them much more efficient.

Note that the setString indices are 1-based, not zero-based.

Upvotes: 6

Vinesh
Vinesh

Reputation: 943

sa.executeUpdate("INSERT INTO history (to, subject, body)"+"VALUES("+ DATA1 + "','" + DATA2 + "','" +DATA3+ "')'");

This code will produce query like this:

INSERT INTO history (to, subject, body)VALUES(vinesh','raja','1111')'

You have to remove single quotes after the last ')' and add single quote after 'VALUES'.

Instead try this code:

sa.executeUpdate("INSERT INTO history (to, subject, body)"+"VALUES('"+ DATA1 + "','" + DATA2 + "','" +DATA3+ "')");

Upvotes: 1

Related Questions