Work with databases in Java. JDBC Tutorial for students of universities Author: Dudnik Oxana
The JDBC API The JDBC API provides programmatic access to relational data from the Java programming language.
JDBC Architecture Two-tier Processing Models
JDBC Architecture Three-tier Processing Models
Get connection with database static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/EMP"; static final String USER = "username"; static final String PASS = "password"; public Connection getConnection() throws SQLException { Connection conn = null; try { //Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected to database"); }catch(Exception e){ e.printStackTrace(); } return conn; }
Statement. Execute a query Statement stmt = null; try{ System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); // Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } //Clean-up environment rs.close(); stmt.close(); }catch(SQLException se) {se.printStackTrace();}
PrepareStatement. PreparedStatement ps = conn.prepareStatement("insert into flowers_table values(?,?)"); int a = 1; String b = "rose"; ps.setString(1,a); ps.setString(2,b); ps.executeUpdate() ;
Literature _java_BD.htmlhttp:// _java_BD.html