· 8 years ago · Apr 12, 2018, 09:00 AM
1package database.demo;
2
3import java.sql.Connection;
4import java.sql.DriverManager;
5import java.sql.PreparedStatement;
6import java.util.Scanner;
7
8/**
9 * Created by Deni on 12.4.2018..
10 */
11public class DatabaseManual {
12 public static void main(String[] args) throws Exception{
13
14 createTable();
15 post();
16
17 }
18
19 public static void post()throws Exception{
20 Scanner scan = new Scanner(System.in);
21 String name = "Deni";
22 String last_name = "Ninkovic";
23
24 try {
25 Connection conn = getConnection();
26 PreparedStatement posted = conn.prepareStatement("INSERT INTO manual_table (FIRST , LAST) VALUES (`"+name+"`, `"+last_name+"`)");
27 posted.executeUpdate();
28 }catch (Exception e){
29 System.out.println(e);
30 }finally {
31 System.out.println("Insert completed.");
32 }
33
34 }
35
36 public static void createTable() throws Exception{
37 try{
38 Connection conn = getConnection();
39 PreparedStatement create = conn.prepareStatement("CREATE TABLE IF NOT EXISTS manual_table(ID INT NOT NULL AUTO_INCREMENT, FIRST VARCHAR(40), LAST VARCHAR(40), PRIMARY KEY (ID))");
40 create.executeUpdate();
41
42 }catch (Exception e){
43 System.out.println(e);
44 }finally {
45 System.out.println("Function complite.");
46 }
47 }
48
49 public static Connection getConnection() throws Exception {
50
51 try {
52 String driver = "com.mysql.jdbc.Driver";
53 String url = "jdbc:mysql://localhost:3306/sakila?useSSL=false";
54 String username = "root";
55 String password = "root";
56 Class.forName(driver);
57
58 Connection conn = DriverManager.getConnection(url, username, password);
59 System.out.println("Connected");
60 return conn;
61 } catch (Exception e) {
62 System.out.println(e);
63 }
64
65
66 return null;
67 }
68}