-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathjavaconnectmysql.java
More file actions
76 lines (60 loc) · 1.76 KB
/
javaconnectmysql.java
File metadata and controls
76 lines (60 loc) · 1.76 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
package com.tutorialsdojo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
/**
* How to connect to a mySQL Database.
*
* @author Jon Bonso
*
*/
public class DatabaseConnection {
public static void main(String[] args) {
try {
connectToDB();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* Connect to MySQL Database
* @throws SQLException
*/
private static void connectToDB() throws SQLException{
// 1. Get the Connection instance using the DriverManager.getConnection() method
// with your MySQL Database Credentails
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tutorialsdojo",
"tutorialsdojo", "P@sSword123");
System.out.println("LOG: Connection Established!");
// 2. Execute your SQL Query using conn.createStatement.executeQuery()
// and get the result as a ResultSet object.
// with your MySQL Database Credentails
ResultSet rs = conn.createStatement().executeQuery("select now()");
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("Query Results: \n\n");
// Show Column Names
getColumnNames(rsmd);
// Getting the Results
while (rs.next()){
for ( int i=1; i <= rsmd.getColumnCount(); i++){;
System.out.print(rs.getString(i) + "\t\t");
}
System.out.println();
}
}
/**
* Shows the Column Names
* @param rs
* @throws SQLException
*/
private static void getColumnNames(ResultSetMetaData rsmd) throws SQLException{
// Getting the list of COLUMN Names
for ( int i=1; i <= rsmd.getColumnCount(); i++){
System.out.print(rsmd.getColumnName(i) + "\t\t|");
}
System.out.println("");
}
}