Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class MySQLAccess {
- private Connection connect = null;
- private Statement statement = null;
- private ResultSet resultSet = null;
- public void readDataBase() throws Exception {
- try {
- // This will load the MySQL driver, each DB has its own driver
- Class.forName("com.mysql.jdbc.Driver");
- // Setup the connection with the DB
- connect = DriverManager
- .getConnection("jdbc:mysql://localhost/merx?"
- + "user=root&password=admin");
- // Statements allow to issue SQL queries to the database
- statement = connect.createStatement();
- // Result set get the result of the SQL query
- resultSet = statement
- .executeQuery("select * from merx.inventory;");
- writeResultSet(resultSet);
- } catch (Exception e) {
- throw e;
- } finally {
- close();
- }
- }
- private void writeResultSet(ResultSet resultSet) throws SQLException {
- ResultSetMetaData resMeta = resultSet.getMetaData();
- int colCount = resMeta.getColumnCount();
- while (resultSet.next()) {
- for (int i = 1; i <= colCount - 1; i++) {
- System.out.print(resultSet.getObject(i).toString() + "|");
- }
- System.out.println(resultSet.getObject(colCount).toString());
- }
- }
- // You need to close the resultSet
- private void close() {
- try {
- if (resultSet != null) {
- resultSet.close();
- }
- if (statement != null) {
- statement.close();
- }
- if (connect != null) {
- connect.close();
- }
- } catch (Exception e) {
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement