Advertisement
Guest User

Untitled

a guest
Aug 5th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1. package com;
  2.  
  3. import java.sql.*;
  4.  
  5. public class TestPStatement implements Runnable {
  6.  
  7.     private final String DB_URL  = "jdbc:mysql://localhost:3306/test";
  8.     private final String DB_USER = "root";
  9.     private final String DB_PASS = "root";
  10.  
  11.     private final String[] fNames = {"Peter", "Ivan", "Peter", "Ivan"};
  12.     private final String[] lNames = {"Ivanov", "Petrov", "Petrov", "Ivanov"};
  13.  
  14.     public static void main(String[] args) {
  15.         new TestPStatement().run();
  16.     }
  17.  
  18.     public void run() {
  19.         Connection connection = null;
  20.         try {
  21.             connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
  22.            
  23.             Statement statement = connection.createStatement();
  24.             statement.addBatch("DROP TABLE IF EXISTS users");
  25.             statement.addBatch("CREATE TABLE users (id int PRIMARY KEY, firstName varchar(30), lastName varchar(30))");
  26.             statement.executeBatch();
  27.  
  28.             PreparedStatement addUser = connection.prepareStatement("INSERT INTO users (id, firstName, LastName) VALUES (?, ?, ?)");
  29.             for (int i = 0; i < fNames.length; i++) {
  30.                 addUser.setLong(1, i);
  31.                 addUser.setString(2, fNames[i]);
  32.                 addUser.setString(3, lNames[i]);
  33.                 addUser.addBatch();
  34.             }
  35.             addUser.executeBatch();
  36.  
  37.             PreparedStatement showUsers = connection.prepareStatement("select * from users where firstName like ?");
  38.             showUsers.setString(1, "P%");
  39.             showUsers.execute();
  40.  
  41.             ResultSet rs = showUsers.getResultSet();
  42.             while (rs.next()) {
  43.                 System.out.print(rs.getString("firstName"));
  44.                 System.out.print(" ");
  45.                 System.out.println(rs.getString("lastName"));
  46.             }
  47.  
  48.         } catch (SQLException e) {
  49.             e.printStackTrace();
  50.         } finally {
  51.             try {
  52.                 connection.close();
  53.             } catch (SQLException e) {
  54.                 e.printStackTrace();
  55.             }
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement