· 5 years ago · Sep 02, 2020, 03:32 PM
1package javacode;
2import java.sql.Connection;
3import java.sql.DriverManager;
4import java.sql.PreparedStatement;
5import java.sql.SQLException;
6import java.util.logging.Level;
7import java.util.logging.Logger;
8public class EducationDatabase {
9 //Database connection
10 public static Connection databaseConnection() {
11 try{
12 Class.forName("com.mysql.cj.jdbc.Driver");
13 //Set server Time zone
14 Connection con = DriverManager.getConnection(
15 "jdbc:mysql://localhost:3306/educationn?useUnicode=true&useJDBCCompliantTimezoneShift=true&serverTimezone=UTCjdbc:mysql://localhost:3306/moneywallet?useUnicode=true&useJDBCCompliantTimezoneShift=true&serverTimezone=UTC",
16 "root",
17 "");
18 System.out.println("successful connection");
19 return con;
20
21 }
22 catch (ClassNotFoundException ex)
23 {
24 Logger.getLogger(EducationDatabase.class.getName()).log(Level.SEVERE,null,ex);
25 ex.printStackTrace();
26 }
27 catch (SQLException ex)
28 {
29 Logger.getLogger(EducationDatabase.class.getName()).log(Level.SEVERE,null,ex);
30 ex.printStackTrace();
31 }
32 return null;
33
34 }
35 //Creating tables
36 public static void createTable() {
37 try
38 {
39 Connection con=databaseConnection();
40 PreparedStatement create= con.prepareStatement(" CREATE TABLE IF NOT EXISTS students(studentId int(11) NOT NULL AUTO_INCREMENT,`name` varchar(250),PRIMARY KEY(studentId), courseId int ,FOREIGN KEY (courseId) REFERENCES courses(courseId))");
41 create.executeUpdate();
42 create= con.prepareStatement(" CREATE TABLE IF NOT EXISTS courses(courseId int(11) NOT NULL AUTO_INCREMENT,`name` varchar(250),PRIMARY KEY(courseId))");
43 create.executeUpdate();
44 create= con.prepareStatement(" CREATE TABLE IF NOT EXISTS institutions (institutionId int(11) NOT NULL AUTO_INCREMENT,`name` varchar(250),PRIMARY KEY(institutionId))");
45 create.executeUpdate();
46 }
47 catch(Exception e)
48 {
49 System.out.println("exception"+e);
50 }
51 //check if table has been created
52 finally {
53 System.out.println("Table created successfully");
54 }
55
56 }
57 public static void main(String[] args) throws Exception {
58 databaseConnection();
59 createTable();
60 }
61}
62