· 8 years ago · Jan 12, 2018, 05:34 PM
1package com.company;
2
3import java.sql.Connection;
4import java.sql.DriverManager;
5import java.sql.PreparedStatement;
6import java.sql.ResultSet;
7import java.util.ArrayList;
8
9/* Grzegorz Kopacz
10 Jan Niewiarowski
11 Adam Maciak
12 */
13
14public class Main {
15
16 public static void main(String[] args) throws Exception {
17
18 get();
19 }
20
21 public static ArrayList<String> get() throws Exception {
22 try {
23 Connection connection = getConnection();
24 PreparedStatement statement = connection.prepareStatement("SELECT first, last from test3");
25 ResultSet resultSet = statement.executeQuery();
26 ArrayList<String> arrayList = new ArrayList<>();
27
28 while (resultSet.next()) {
29 System.out.println("First name: " + resultSet.getString("first"));
30 System.out.println("Last name: " + resultSet.getString("last"));
31 arrayList.add(resultSet.getString("last"));
32 }
33 System.out.println("All records selected.");
34 return arrayList;
35 } catch (Exception e) {
36 System.out.println(e);
37 }
38 return null;
39
40 }
41
42
43 public static void post() throws Exception {
44 final String var1 = "Jan";
45 final String var2 = "NOWAK";
46 try {
47 Connection connection = getConnection();
48 PreparedStatement posted = connection.prepareStatement("INSERT INTO test3 (first,last) VALUES ('" + var1 + "', '" + var2 + "')");
49 posted.executeUpdate();
50 } catch (Exception e) {
51 System.out.println(e);
52 } finally {
53 System.out.println("Function INSERT completed.");
54 }
55
56 }
57
58 public static void createTable() throws Exception {
59 try {
60 Connection connection = getConnection();
61 PreparedStatement create = connection.prepareStatement("CREATE TABLE IF NOT EXISTS test3(id int NOT NULL AUTO_INCREMENT,first varchar(255),last varchar(255),PRIMARY KEY(id))"); //w nawiasach mają być parametry tworzonej tabeli
62 create.executeUpdate();
63
64 } catch (Exception e) {
65 System.out.println(e);
66 } finally {
67 System.out.println("Function Complete");
68 }
69 }
70
71
72 public static Connection getConnection() throws Exception {
73 try {
74 String driver = "com.mysql.jdbc.Driver";
75 String url = "jdbc:mysql://localhost:3306/firma";
76 String username = "root";
77 String password = "Grunwaldzka16";
78 Class.forName(driver);
79
80 Connection connection = DriverManager.getConnection(url, username, password);
81 System.out.println("CONNECTED");
82 return connection;
83 } catch (Exception e) {
84 System.out.println(e);
85 }
86
87 return null;
88 }
89}