· 10 years ago · Apr 15, 2016, 07:03 AM
1package com.company;
2
3import java.sql.*;
4
5public class Main {
6
7 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; //Configure the driver needed
8 static final String DB_CONNECTION_URL = "jdbc:mysql://localhost:3306/vet"; //Connection string – where's the database?
9 static final String USER = "clara"; //TODO replace with your username
10 static final String PASSWORD = "password"; //TODO replace with your password
11
12 public static void main(String[] args) {
13
14 try {
15
16 Class.forName(JDBC_DRIVER);
17
18 } catch (ClassNotFoundException cnfe) {
19 System.out.println("Can't instantiate driver class; check you have drivers and classpath configured correctly?");
20 cnfe.printStackTrace();
21 System.exit(-1); //No driver? Need to fix before anything else will work. So quit the program
22 }
23
24 Statement statement = null;
25 Connection conn = null;
26
27 try {
28
29 //You should have already created a database via terminal/command prompt OR MySQL Workbench
30
31 conn = DriverManager.getConnection(DB_CONNECTION_URL, USER, PASSWORD);
32 statement = conn.createStatement();
33
34 //Create a table in the database, if it does not exist already
35 String createTableSQL = "CREATE TABLE IF NOT EXISTS dogs (Name varchar(30), Age int)";
36 statement.executeUpdate(createTableSQL);
37 System.out.println("Created Dogs table");
38
39 //Add some data
40 String addDataSQL = "INSERT INTO dogs VALUES ('Poppy', 3)";
41 statement.executeUpdate(addDataSQL);
42
43 addDataSQL = "INSERT INTO dogs VALUES ('Zelda', 5)";
44 statement.executeUpdate(addDataSQL);
45 System.out.println("Added two rows of data");
46
47 } catch (SQLException se) {
48 se.printStackTrace();
49 } catch (Exception e) {
50 e.printStackTrace();
51 } finally {
52 //A finally block runs whether an exception is thrown or not. Close resources and tidy up whether this code worked or not.
53 try {
54 if (statement != null) {
55 statement.close();
56 System.out.println("Statement closed");
57 }
58 } catch (SQLException se){
59 //Closing the connection could throw an exception too
60 se.printStackTrace();
61 }
62 try {
63 if (conn != null) {
64 conn.close(); //Close connection to database
65 System.out.println("Database connection closed");
66 }
67 } catch (SQLException se) {
68 se.printStackTrace();
69 }
70 }
71 System.out.println("End of program");
72 }
73}