Advertisement
Guest User

Untitled

a guest
Jul 4th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1.  
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6.  
  7. /**
  8.  * Created by andredsnogueira on 03/07/16.
  9.  */
  10.  
  11. public class DBConnect {
  12.     private Connection con;
  13.     private Statement st;
  14.     private ResultSet rs;
  15.  
  16.     public DBConnect(){
  17.         try{
  18.             Class.forName("com.mysql.jdbc.Driver");
  19.             con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbintellij","andre","");
  20.             st = con.createStatement();
  21.         }catch (Exception e){
  22.             System.out.println(e + " connect");
  23.         }
  24.     }
  25.  
  26.     public void getData(){
  27.         try{
  28.             String query = "select * from persons";
  29.             rs = st.executeQuery(query);
  30.             System.out.println("Records from db");
  31.             while(rs.next()){
  32.                 String name = rs.getString("name");
  33.                 String age = rs.getString("age");
  34.                 System.out.println("Name: "+name+"   Age: "+age);
  35.             }
  36.  
  37.  
  38.         }catch (Exception e){
  39.             System.out.println(e + " get");
  40.         }
  41.     }
  42.  
  43.     public void insertData(){
  44.         try{
  45.             Class.forName("com.mysql.jdbc.Driver");
  46.             con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbintellij","andre","");
  47.             st = con.createStatement();
  48.             String sql= "insert into persons"+ " (id, name, age)" + " values(5, 'Kiko', '20')";
  49.             st.executeLargeUpdate(sql);
  50.             System.out.println("Inserted");
  51.         }catch (Exception e){
  52.             System.out.println(e + " insert");
  53.         }
  54.     }
  55.  
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement