· 9 years ago · Aug 04, 2017, 09:30 PM
1package database;
2
3import java.io.File;
4import java.io.FileWriter;
5import java.io.IOException;
6import java.sql.Connection;
7import java.sql.DriverManager;
8import java.sql.PreparedStatement;
9import java.sql.ResultSet;
10import java.util.ArrayList;
11
12public class main {
13
14
15 public static void main(String [] args) throws Exception {
16
17 createTable();
18 einsetzen();
19 get();
20 }
21 public static ArrayList<String> get() throws Exception {
22 try {
23 Connection con = getConnection();
24
25
26 PreparedStatement statement = con.prepareStatement("SELECT Funktion, Wert FROM config");
27
28 ResultSet result = statement.executeQuery();
29
30 ArrayList<String> array = new ArrayList<String>();
31
32
33
34
35 while(result.next()) {
36
37
38 System.out.print(result.getString("Funktion"));
39 System.out.print(" ");
40 System.out.println(result.getString("Wert"));
41
42 array.add(result.getString("Funktion"));
43 array.add(" ");
44 array.add(result.getString("Wert"));
45 array.add(System.getProperty("line.separator"));
46 }
47
48
49 return array;
50 }catch(Exception e) {
51 System.out.println(e);
52 }
53 return null;
54 }
55 public static void einsetzen() throws Exception {
56
57 try {
58 Connection con = getConnection();
59
60
61 PreparedStatement einsetzen = con.prepareStatement("INSERT INTO config (Funktion, Wert) VALUES (' test ','1') ");
62 einsetzen.executeUpdate();
63 }catch(Exception e) {
64 System.out.println(e);
65 }
66 finally {
67 System.out.println("Default Werte eingesetzt");
68 }
69 }
70 public static void createTable() throws Exception {
71 try {
72 Connection con = getConnection();
73
74 PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS config(Funktion VARCHAR(100),Wert INT(100), PRIMARY KEY(Funktion))");
75 create.executeUpdate();
76
77 }catch(Exception e) {
78 System.out.println(e);
79 }
80 finally {
81 System.out.println("Function executed");
82 }
83 }
84 public static Connection getConnection() throws Exception{
85
86 try {
87 String host = "sql8.freesqldatabase.com";
88 String port = "3306";
89 String database = "sql8188659";
90 String username = "sql8188659";
91 String password = "9BsTH3YGPy";
92
93
94 String driver = "com.mysql.jdbc.Driver";
95 String url = "jdbc:mysql://"+ host +":"+ port +"/"+ database ;
96
97 Class.forName(driver);
98
99 Connection conn = DriverManager.getConnection(url, username, password);
100
101 System.out.println("Connected");
102
103 return conn;
104
105 } catch(Exception e) {
106 System.out.println(e);
107 }
108
109 return null;
110
111 }
112
113
114}