Advertisement
Guest User

Untitled

a guest
Aug 2nd, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. package mysql;
  2.  
  3. import java.sql.*;
  4. import java.util.Scanner;
  5.  
  6. public class AddProductMain {
  7.  
  8. private static final String INSERT_PRODUCT_QUERY =
  9. "INSERT INTO products(name, description, price)" +
  10. " VALUES(?,?,?)";
  11.  
  12. public static void main(String[] args){
  13. String url = "jdbc:mysql://localhost:3306/products_ex";
  14.  
  15. Scanner scanner = new Scanner(System.in);
  16. String name = scanner.next();
  17. String description = scanner.next();
  18. double price = scanner.nextDouble();
  19.  
  20. System.out.println(name + description + price);
  21.  
  22. try(Connection connection = getConnection(url)){
  23. int id = addProduct(connection, name, description, price);
  24. System.out.println("Product id = " + id);
  25. } catch (SQLException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29.  
  30. public static int addProduct(Connection connection,
  31. String name, String description,
  32. double price) throws SQLException {
  33. String[] ids = {"id"};
  34. try(PreparedStatement preparedStatement =
  35. connection.prepareStatement(INSERT_PRODUCT_QUERY,ids)){
  36. preparedStatement.setString(1, name);
  37. preparedStatement.setString(2, description);
  38. preparedStatement.setDouble(3, price);
  39. int i = preparedStatement.executeUpdate();
  40.  
  41. if(i != 1){
  42. System.out.println("Product was not added to table");
  43. }else{
  44. System.out.println("Product was added to table");
  45. }
  46.  
  47. try(ResultSet generatedKeys = preparedStatement.getGeneratedKeys()){
  48. while (generatedKeys.next()){
  49. return generatedKeys.getInt(1);
  50. }
  51. }
  52. }
  53. throw new RuntimeException("Product was not added to table");
  54.  
  55. }
  56.  
  57. private static Connection getConnection(String url) throws SQLException {
  58. return DriverManager.getConnection(url,"root", "root");
  59. }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement