Advertisement
Guest User

Untitled

a guest
Mar 30th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6.  
  7. public class Main {
  8.     public static void main(String[] args) throws SQLException {
  9.  
  10.         Statement statement = null;
  11.         PreparedStatement preparedStatement = null;
  12.        
  13.         try(Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1375")) {
  14.            
  15.             String data = "C:\\data\\help\\target2018.txt";
  16.            
  17.             // With normal statement the insert query will store wrong value.
  18.             statement = connection.createStatement();
  19.             String query = "INSERT INTO train(path) VALUES('" + data + "');";
  20.             // The query will be "INSERT INTO train(path) VALUES('C:\data\help\target.txt');"
  21.             // which causes MySQL to remove all backslashes from it.
  22.             statement.executeUpdate(query);// MySQL will store the value "C:datahelptarget.txt".
  23.  
  24.            
  25.             // With PreparedStatement the insert query will succeed.
  26.             preparedStatement = connection.prepareStatement("INSERT INTO train(path) VALUES(?);");
  27.             preparedStatement.setString(1, data);
  28.             // PreparedStatement will format the query and force double backslashes in the query
  29.             // The query will be "INSERT INTO train(path) VALUES('C:\\data\\help\\target.txt');"
  30.             preparedStatement.executeUpdate();
  31.  
  32.         } catch (SQLException ex) {
  33.             if(statement != null) statement.close();
  34.             if(preparedStatement != null) statement.close();
  35.             ex.printStackTrace();
  36.         }
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement