· 8 years ago · May 17, 2018, 04:22 AM
1package database;
2
3import java.sql.Connection;
4import java.sql.DriverManager;
5import java.sql.PreparedStatement;
6import java.sql.ResultSet;
7import java.util.ArrayList;
8
9public class Main {
10
11 public static void main(String[] args) throws Exception {
12 // TODO Auto-generated method stub
13 createTable();
14 post();
15 get();
16
17
18 }
19 public static ArrayList<String> get() throws Exception{
20 try{
21 Connection con = getConnection();
22 PreparedStatement statement = con.prepareStatement("SELECT * FROM iamalive ORDER BY first DESC LIMIT 1");
23
24 ResultSet result = statement.executeQuery();
25
26 ArrayList<String> array = new ArrayList<String>();
27 while(result.next()){
28 System.out.print(result.getString("first"));
29 System.out.print(" ");
30 System.out.println(result.getString("last"));
31
32 array.add(result.getString("last"));
33 }
34 System.out.println("All records have been selected!");
35 return array;
36
37 }catch(Exception e){System.out.println(e);}
38 return null;
39
40 }
41 public static void post() throws Exception{
42 final String var1 = "John";
43 final String var2 = "Miller";
44 try{
45 Connection con = getConnection();
46 PreparedStatement posted = con.prepareStatement("INSERT INTO iamalive (first, last) VALUES ('"+var1+"', '"+var2+"')");
47
48 posted.executeUpdate();
49 } catch(Exception e){System.out.println(e);}
50 finally {
51 System.out.println("Insert Completed.");
52 }
53 }
54 public static void createTable() throws Exception{
55 try{
56 Connection con = getConnection();
57 PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS iamalive(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))");
58 create.executeUpdate();
59 }catch(Exception e){System.out.println(e);}
60 finally{
61 System.out.println("Function Complete.");
62 };
63
64 }
65 public static Connection getConnection() throws Exception{
66 try{
67 String driver = "com.mysql.jdbc.Driver";
68 String url = "jdbc:mysql://24.196.52.166:3306/testdb";
69 String username = "javadata";
70 String password = "mypass";
71 Class.forName(driver);
72
73 Connection conn = DriverManager.getConnection(url,username,password);
74 System.out.println("Connected");
75 return conn;
76 } catch(Exception e){System.out.println(e);}
77
78
79 return null;
80 }
81
82}