I'm VERY new to JDBC and am trying to work on a project for a class. We are supposed to create a database and relations for said database. If the database or relations already exist, we are supposed to print a message notifying the user. I'm not really sure how to do that. This is what I have so far for my methods:
public static void createDatabase() throws Exception {
String createString =
"CREATE DATABASE IF NOT EXISTS companydb";
Statement stmt = null;
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/?autoReconnect=true&useSSL=false";
String username = "username";
String password = "password";
Class.forName(driver);
Connection con = DriverManager.getConnection(url, username, password);
stmt = con.createStatement();
stmt.executeUpdate(createString);
System.out.println("Database created.");
} catch (Exception e) {
System.out.println(e);
} finally {
if (stmt != null) { stmt.close();
}
}
}
And for creating an employee table (not all values are created yet, just a test run):
public static void createEmployeeTable() throws Exception {
String createString =
"create table if not exists employee" + "(Fname char(32) NOT NULL, " +
PRIMARY KEY(Fname)";
Statement stmt = null;
try {
Connection con = getConnection();
stmt = con.createStatement();
stmt.executeUpdate(createString);
System.out.println("Employee table created.");
} catch (Exception e) {
System.out.println(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
Also I realize creating a table like that might not be the most efficient way to make a relation, but it's just a work in progress right now. Thanks for any help anyone can provide!
Regardless of if the database and relations/tables already exist or not, it puts out the same output:
Database created.
Connected to database.
Employee table created.
Connected to database.
Department table created.
Connected to database.
Project table created.
Connected to database.
Works_On table created.