Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- public class SQLDatabase {
- private Connection connect;
- private Statement statement;
- private ResultSet resultSet;
- private String url;
- private String userName;
- private String password;
- public SQLDatabase(String database, String user, String passwd)
- throws InstantiationException, IllegalAccessException,
- ClassNotFoundException, SQLException {
- url = "jdbc:mysql://195.56.52.249/" + database;
- userName = user;
- password = passwd;
- connect();
- }
- private void connect() throws InstantiationException,
- IllegalAccessException, ClassNotFoundException, SQLException {
- Class.forName("com.mysql.jdbc.Driver").newInstance();
- connect = DriverManager.getConnection(url, userName, password);
- System.out.println("Connected to database.");
- }
- public void readDatabase() throws SQLException {
- statement = connect.createStatement();
- resultSet = statement.executeQuery("SELECT * FROM test");
- getValues(resultSet);
- getMetaData(resultSet);
- }
- private void getMetaData(ResultSet resultSet) throws SQLException {
- System.out.println("The columns in the table are: ");
- System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
- for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
- System.out.println("Column " + i + " "
- + resultSet.getMetaData().getColumnName(i));
- }
- }
- private void getValues(ResultSet resultSet) throws SQLException {
- while (resultSet.next()) {
- int ID = resultSet.getInt("ID");
- String name = resultSet.getString("Nev");
- String cim = resultSet.getString("Cim");
- System.out.println("ID: " + ID);
- System.out.println("Nev: " + name);
- System.out.println("Cim: " + cim);
- }
- }
- public static void main(String[] args) {
- try {
- SQLDatabase db = new SQLDatabase("test", "prog", "prog");
- db.readDatabase();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- System.err.println("Error message: " + e.getMessage());
- System.err.println("Error number: " + e.getErrorCode());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement