-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mariadb.java
66 lines (55 loc) · 2.06 KB
/
Mariadb.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//STEP 1. Import required packages
//package mariadb;
import java.sql.*;
// From: https://stackoverflow.com/questions/37909487/how-can-i-connect-to-mariadb-using-java
public class Mariadb {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
static final String DB_URL = "jdbc:mariadb://mariadb/mydb";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("org.mariadb.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
stmt = conn.createStatement();
String sql = "SELECT VERSION();";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
System.out.println(rs.getString(1));
}
System.out.println("Done.");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
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
System.out.println("Goodbye!");
}//end main
}//end JDBCExample