Инструменты пользователя

Инструменты сайта


prog:mysql-java
test.java
import java.sql.*;
public class test {
    public static void main(String args[]) {
        System.out.println("стартуем");
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            // Подгружаем драйвер
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception e) {
            System.out.println("failed to load jdbc driver class");
            System.exit(0);
        }
        try {
            // Работаем с БД
            conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/news?user=NEWSREADER&password=READERPASSWORD"
            );
            st = conn.createStatement();
            rs = st.executeQuery("select * from news order by id desc");
            while (rs.next()) {
                System.out.println(rs.getString("header"));
            }
        } catch (SQLException e) {
            // Ругаемся на ошибки
            if (conn == null) {
                System.out.println("failed to connect to database");
            } else
            if (st == null) {
                System.out.println("failed to create statement");
            } else
            if (rs == null) {
                System.out.println("failed to fetch resultset");
            } else {
                System.out.println("error while fetching results");
            }
        } finally {
            // Да, пустые блоки catch - очень плохо
            if (rs != null) {
                try { rs.close(); } catch (Exception e) {}
            }
            if (st != null) {
                try { st.close(); } catch (Exception e) {}
            }
            if (conn != null) {
                try { conn.close(); } catch (Exception e) {}
            }
        }
        System.out.println("финишируем");
    }
}
prog/mysql-java.txt · Последнее изменение: 2024/05/02 13:20 — 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki