java数据库-JDBC

来源:互联网 发布:物业管理需求什么软件 编辑:程序博客网 时间:2024/06/08 09:09

首先什么是JDBC?

JDBC 是用于执行SQL语句的java API,是java程序连接数据库的纽带。JDBC不能知己访问数据库,

而是通过数据库产商提供的驱动程序。

JDBC中 常用的接口和类:

DriverManager 类:管理数据库中的驱动程序,是JDBC的管理层,作用于用户和驱动程序之间。

通过 getConnection(String url,String user,String pass)可以获取Connection 实例。

Statement 接口:主要是用于执行静态的SQL语句,现在 用得少

PreparedStatement接口:用于执行动态的SQL语句。继承自 Statement 类


建立JDBC连接的基本步骤:

导入JDBC相关的JAR包-->注册JDBC的驱动程序-->数据库URL连接配置-->创建连接,DriverManager对象的getConnection()方法。


import java.sql.*;public class database {private final static String DRIVER = "com.mysql.jdbc.Driver";private final static String URL = "mysql://hostlocal:3306/acc";private final static String NAME = "root";private final static String PASSWORD = "";public Connection con = null;public PreparedStatement st = null;public ResultSet rs = null;static{try{Class.forName(DRIVER);}catch (ClassNotFoundException e) {e.printStackTrace();}}public Connection getCon(){try{con = DriverManager.getConnection(URL, NAME, PASSWORD);}catch(SQLException e){e.printStackTrace();}return con;}public PreparedStatement getSt(String sql){try {st = con.prepareStatement(sql);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return st;}public ResultSet getRs(){try {rs = st.executeQuery();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return rs;}public void CloseCon(Connection con){try {con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void CloseSt(){try {st.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void CloseRs(){try {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}




0 0