-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySqlExample.java
More file actions
42 lines (38 loc) · 1.57 KB
/
MySqlExample.java
File metadata and controls
42 lines (38 loc) · 1.57 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
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
public class MySqlExample {
public static void main(String[] args) throws ClassNotFoundException {
String host, port, databaseName, userName, password;
host = port = databaseName = userName = password = null;
for (int i = 0; i < args.length - 1; i++) {
switch (args[i].toLowerCase(Locale.ROOT)) {
case "-host": host = args[++i]; break;
case "-username": userName = args[++i]; break;
case "-password": password = args[++i]; break;
case "-database": databaseName = args[++i]; break;
case "-port": port = args[++i]; break;
}
}
// JDBC allows to have nullable username and password
if (host == null || port == null || databaseName == null) {
System.out.println("Host, port, database information is required");
return;
}
Class.forName("com.mysql.cj.jdbc.Driver");
try (final Connection connection =
DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + databaseName + "?sslmode=require", userName, password);
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT version() AS version")) {
while (resultSet.next()) {
System.out.println("Version: " + resultSet.getString("version"));
}
} catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}