HarrJ

DAY28

Jul 20th, 2024
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5.  
  6.  
  7. public class Day28A {
  8.     public static void main(String[] args) {
  9.         Scanner sc = new Scanner(System.in);
  10.         Day28A callMe = new Day28A();
  11.         String pname;
  12.         String pcat;
  13.         double price;
  14.         int qty;
  15.         int rowsAffected;
  16.        
  17.         System.out.println("Enter item to add to row");
  18.         System.out.print("Product name: ");
  19.         pname = sc.nextLine();
  20.         System.out.print("Product category: ");
  21.         pcat = sc.nextLine();
  22.         System.out.print("Product price: ");
  23.         price = sc.nextDouble();
  24.         sc.nextLine();
  25.         System.out.print("Product quantity: ");
  26.         qty = sc.nextInt();
  27.         sc.nextLine();
  28.        
  29.         rowsAffected = callMe.addToTable(pname, pcat, price, qty);
  30.        
  31.         System.out.println(rowsAffected);
  32.     }
  33.    
  34.     int addToTable(String pname, String pcat, double price, int qty){
  35.         int rowsAffected = 0;
  36.         String connString = "jdbc:mysql://localhost:3306/db_sg_b2_24";
  37.         String userName = "root";
  38.         String passWord = "";
  39.         String sqlQuery = "INSERT INTO tbl_price_list(fld_pname, fld_pcategory"
  40.                 + ", fld_price, fld_qty)"
  41.                 + " VALUES (?,?,?,?)";
  42.        
  43.         try {
  44.             Connection conn = DriverManager.getConnection(connString, userName, passWord);
  45.            
  46.             PreparedStatement stmt = conn.prepareStatement(sqlQuery);
  47.             stmt.setString(1, pname);
  48.             stmt.setString(2, pcat);
  49.             stmt.setDouble(3, price);
  50.             stmt.setInt(4, qty);
  51.            
  52.             rowsAffected = stmt.executeUpdate();
  53.            
  54.             conn.close();
  55.         } catch (Exception e) {
  56.             rowsAffected = -1;
  57.            
  58.         }
  59.        
  60.         return rowsAffected;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment