Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mysql;
- import java.sql.*;
- import java.util.Scanner;
- public class AddProductMain {
- private static final String INSERT_PRODUCT_QUERY =
- "INSERT INTO products(name, description, price)" +
- " VALUES(?,?,?)";
- public static void main(String[] args){
- String url = "jdbc:mysql://localhost:3306/products_ex";
- Scanner scanner = new Scanner(System.in);
- String name = scanner.next();
- String description = scanner.next();
- double price = scanner.nextDouble();
- System.out.println(name + description + price);
- try(Connection connection = getConnection(url)){
- int id = addProduct(connection, name, description, price);
- System.out.println("Product id = " + id);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public static int addProduct(Connection connection,
- String name, String description,
- double price) throws SQLException {
- String[] ids = {"id"};
- try(PreparedStatement preparedStatement =
- connection.prepareStatement(INSERT_PRODUCT_QUERY,ids)){
- preparedStatement.setString(1, name);
- preparedStatement.setString(2, description);
- preparedStatement.setDouble(3, price);
- int i = preparedStatement.executeUpdate();
- if(i != 1){
- System.out.println("Product was not added to table");
- }else{
- System.out.println("Product was added to table");
- }
- try(ResultSet generatedKeys = preparedStatement.getGeneratedKeys()){
- while (generatedKeys.next()){
- return generatedKeys.getInt(1);
- }
- }
- }
- throw new RuntimeException("Product was not added to table");
- }
- private static Connection getConnection(String url) throws SQLException {
- return DriverManager.getConnection(url,"root", "root");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement