-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.java
More file actions
90 lines (73 loc) · 2.24 KB
/
database.java
File metadata and controls
90 lines (73 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Project;
import java.sql.*;
import javax.swing.JOptionPane;
public class database{
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/db";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
Connection conn = null;
Statement stmt = null;
public void createConnection()
{
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
JOptionPane.showMessageDialog(null, "Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
JOptionPane.showMessageDialog(null, "Connected database successfully...");
//STEP 4: Execute a query
JOptionPane.showMessageDialog(null,"Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE REGISTRATION " +
"(card_number INTEGER not NULL, " +
" name VARCHAR(255), " +
" h_f_name VARCHAR(255), " +
"department VARCHAR(255),"+
"designation VARCHAR(255),"+
" PRIMARY KEY ( card_number ))";
stmt.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"Created table in given database...");
}
catch(SQLException se)
{
//Handle errors for JDBC
se.printStackTrace();
}
catch(Exception e)
{
//Handle errors for Class.forName
JOptionPane.showMessageDialog(null,"ERROR!");
e.printStackTrace();
}
finally
{
//finally block used to close resources
try
{
if(stmt!=null)
conn.close();
}
catch(SQLException se)
{
}// do nothing
try
{
if(conn!=null)
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}//end finally try
}//end try
JOptionPane.showMessageDialog(null,"Goodbye!");
}//end main
}//end JDBCExample