-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJavaToMySQL.java
49 lines (40 loc) · 1.64 KB
/
JavaToMySQL.java
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
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Simple Java program to connect to MySQL database running on localhost and
* running SELECT and INSERT query to retrieve and add data.
*/
public class JavaToMySQL {
// JDBC URL, username and password of MySQL server
private static final String url = "jdbc:mysql://localhost:3306/attendance";
private static final String user = "root";
private static final String password = "123";
// JDBC variables for opening and managing connection
private static Connection con;
private static Statement stmt;
private static ResultSet rs;
public static void main(String args[]) {
String query = "select * from csc_classcount";
try {
// opening database connection to MySQL server
con = DriverManager.getConnection(url, user, password);
// getting Statement object to execute query
stmt = con.createStatement();
// executing SELECT query
rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString(1)+" : " + rs.getString(2));
}
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
} finally {
//close connection ,stmt and resultset here
try { con.close(); } catch(SQLException se) { /*can't do anything */ }
try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
}
}
}