java中的JDBC 连接数据库的基本步骤

来源:互联网 发布:websocketserver java 编辑:程序博客网 时间:2024/05/21 07:02
  1. 加载数据库驱动到java虚拟机 (Class.forName)
  2. 建立数据库连接(url)
  3. 创建数据库的操作对象 (getConnection)
  4. 定义SQL语句
  5. 执行数据库操作 (execteQuery)
  6. 获取数据集(Resultset)
  7. 关闭数据库对象(Resultset,Statement,Connection)

代码实例:JdbcUtil.java

package dbc;import java.sql.*;import java.util.Properties;public final class JdbcUtil {    private static String driver ="" ;    private static String url = "" ;    private static String user = "" ;    private static String password = "" ;    private static Properties pr=new Properties();    private JdbcUtil(){}    //设计该工具类的静态初始化器中的代码,该代码在装入类时执行,且只执行一次    static {        try {pr.load(JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties"));          driver=pr.getProperty("driver");          url=pr.getProperty("url");          user=pr.getProperty("username");          password=pr.getProperty("password");          Class.forName(driver);        //加载注册驱动程序        } catch (Exception e) {            throw new ExceptionInInitializerError(e);        }    }    //设计获得连接对象的方法getConnection()    public static Connection getConnection() throws SQLException {        return DriverManager.getConnection(url, user, password);     //建立连接    }    //设计释放结果集、语句和连接的方法free()    public static void free(ResultSet rs, Statement st, Connection conn) {        try { if (rs != null) rs.close();        } catch (SQLException e) {e.printStackTrace();        } finally {            try { if (st != null) st.close();            } catch (SQLException e) {e.printStackTrace();            } finally {                  if (conn != null)                    try { conn.close();                    } catch (SQLException e) {e.printStackTrace();}                     }        }     }}

db.properties

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/Car_Sale?useUnicode=true&characterEncoding=utf-8username=rootpassword=root
原创粉丝点击