利用JDBC访问数据库的步骤
?步骤
?1)调用Class类的forName()方法,加载并注册数据库驱动。
?2)调用DriverManager类的getConnection()方法,建立到数据库的连接
?3)调用Connection对象的createStatement()方法,访问数据库
?4)调用Statement对象的executeQuery()方法得到ResultSet对象。
?5) 调用ResultSet对象的getObject()方法,处理结果。
?6)释放资源(连接应该尽可能晚建立,释放资源应尽可能早释放。)
?
下面是初始代码:
?下面是用单例模式编写的代码:
package jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;/** *Jdbc工具类 * @author HaoWang */public class JdbcUtilsSimple { private static String url = "jdbc:mysql://localhost:3306/test"; private static String user = "root"; private static String password = "123456"; private static JdbcUtilsSimple instance = null; private JdbcUtilsSimple() { } public static JdbcUtilsSimple getInstance() { if(instance == null) { synchronized (JdbcUtilsSimple.class) { if(instance == null) { instance = new JdbcUtilsSimple(); } } } return instance; } static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { throw new ExceptionInInitializerError(ex); } } public Connection getConnection() throws SQLException{ return DriverManager.getConnection(url, user, password); } public void free(Connection conn, Statement st, ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException ex) { System.out.println(ex.toString()); } finally { try { if(st!=null) { st.close(); } } catch (SQLException ex) { System.out.println(ex.toString()); } finally { try { if(conn!=null){ conn.close(); } } catch (SQLException ex) { System.out.println(ex.toString()); } } } }}?