Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class Main {
- public static void main(String[] args) throws SQLException {
- Statement statement = null;
- PreparedStatement preparedStatement = null;
- try(Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1375")) {
- String data = "C:\\data\\help\\target2018.txt";
- // With normal statement the insert query will store wrong value.
- statement = connection.createStatement();
- String query = "INSERT INTO train(path) VALUES('" + data + "');";
- // The query will be "INSERT INTO train(path) VALUES('C:\data\help\target.txt');"
- // which causes MySQL to remove all backslashes from it.
- statement.executeUpdate(query);// MySQL will store the value "C:datahelptarget.txt".
- // With PreparedStatement the insert query will succeed.
- preparedStatement = connection.prepareStatement("INSERT INTO train(path) VALUES(?);");
- preparedStatement.setString(1, data);
- // PreparedStatement will format the query and force double backslashes in the query
- // The query will be "INSERT INTO train(path) VALUES('C:\\data\\help\\target.txt');"
- preparedStatement.executeUpdate();
- } catch (SQLException ex) {
- if(statement != null) statement.close();
- if(preparedStatement != null) statement.close();
- ex.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement