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.SQLException;
- import java.sql.Statement;
- import java.util.Date;
- public class JDBCExample {
- // jdbc driver name and database url
- static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
- static final String JDBC_URL = "jdbc:mysql://localhost/db";
- // Database credentials
- static final String USER = "root";
- static final String PASS = "";
- public static void main(String[] args) {
- Connection connection = null;
- Statement statement = null;
- try {
- // register jdbc driver
- Class.forName(JDBC_DRIVER);
- // open a connection
- System.out.println("Connection to database...");
- connection = DriverManager.getConnection(JDBC_URL, USER, PASS);
- // execute a query
- System.out.println("Creating a statement...");
- statement = connection.createStatement();
- String sql = "SELECT * FROM people;";
- ResultSet resultSet = statement.executeQuery(sql);
- // extract data from dataset
- while(resultSet.next()) {
- int id = resultSet.getInt("id");
- String firstName = resultSet.getString("first_name");
- String lastName = resultSet.getString("last_name");
- Date birth = resultSet.getDate("birth");
- Date death = resultSet.getDate("death");
- int professionsId = resultSet.getInt("professions_id");
- System.out.println("id: " + id);
- System.out.println("firstName: " + firstName);
- System.out.println("lastName: " + lastName);
- System.out.println("birth: " + birth);
- System.out.println("death: " + death);
- System.out.println("professionsId: " + professionsId);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } finally {
- try {
- if(statement != null) {
- statement.close();
- }
- } catch (SQLException e) {
- }
- try {
- if(connection != null) {
- connection.close();
- }
- } catch (Exception e) {
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement