JDBC is a Java techonology to access databases. JDBC APIs allow a developer to load a particular JDBC driver, via a component called JDBC driver manager. The advantage of this is that you are not writing for a specific database and it's easy to switch.
Depending on the needs there are different kinds of JDBC drivers:
This is an example of query using JDBC:
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school","root",""); Statement st = conn.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = st.executeQuery("select * from students");) { while(rs.next()) System.out.println(rs.getString("firstName") + "\t" + rs.getString("lastName") ); } catch (SQLException e) { // This is just an example... in a real application you would have to // manage this exception. e.printStackTrace(); }
This is the way a writing operation is usually done:
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school","root",""); Statement st = conn.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ) { st.executeUpdate("update students set name=\"Bobo\" where name=\"Boby\""); } catch (SQLException e) { // This is just an example... in a real application you would have to // manage this exception. e.printStackTrace(); }
Use executeQuery() if the operation returns a ResultSet
Use execute() if the operation returns more than one ResultSet and retrieve them by calling Statement.getResultSet()
Use executeUpdate() if the operation is an update, insert or delete
There are three types of Statement you can use:
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.