package com.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Demo {
public static void main(String[] args) {
System.out.println("count: " + count());
}
private static long count() {
long result = 0;
try {
PreparedStatement preparedStatement = ConnectDB.connection()
.prepareStatement("select count(*) from mobile");
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
result = resultSet.getLong(1);
} catch (Exception e) {
result = 0;
} finally {
ConnectDB.disconnect();
}
return result;
}
public class ConnectDB {
private static Connection connection;
public static Connection connection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database", "username",
"password");
} catch (Exception e) {
e.printStackTrace();
connection = null;
}
return connection;
}
public static void disconnect() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}