· 7 years ago · Dec 05, 2018, 06:28 PM
1import java.sql.Connection;
2import java.sql.DriverManager;
3import java.sql.SQLException;
4import java.sql.Statement;
5
6public class ConnectionToDataBase {
7
8 private Connection connection = null;
9 private Statement statement;
10
11 public Connection getConnection() {
12 try
13 {
14 Class.forName("com.mysql.jdbc.Driver");
15 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/","root","");
16 System.out.println("Success!");
17 }
18 catch(Exception e) {
19 System.out.println(e);
20 }
21 return connection;
22 }
23
24 private void createDatabase(String databaseName) {
25 try {
26 this.connection = getConnection();
27 Statement s = connection.createStatement();
28 s.executeUpdate("CREATE DATABASE IF NOT EXISTS " + databaseName);
29 this.connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+databaseName,"root","");
30 }
31 catch (SQLException e) {
32 e.printStackTrace();
33 }
34 }
35
36 public void createTable(String tableName) {
37 String myTableName = "CREATE TABLE " + tableName + " ( "
38 + "id INT(64) NOT NULL AUTO_INCREMENT,"
39 + "name VARCHAR(20),"
40 + "date DATE,"
41 + "agentCount INT(64), "
42 + "PRIMARY KEY (`id`))";
43 try {
44 statement = connection.createStatement();
45 //This line has the issue
46 statement.executeUpdate(myTableName);
47 System.out.println("Table Created");
48 } catch (SQLException e ) {
49 System.out.println("An error has occured on Table Creation");
50 e.printStackTrace();
51 }
52 }
53
54 public static void main(String[] args) {
55 ConnectionToDataBase c = new ConnectionToDataBase();
56 c.createDatabase("sashoDB");
57 c.createTable("myNewTable");
58 }
59}