JDBC数据库编程
一、JDBC
JDBC制定了统一访问各类关系数据库的标准接口,为各个数据库厂商提供了标准接口的实现
JDBC规范将驱动程序归结为以下几类(选自Core Java Volume Ⅱ——Advanced Features):
- 第一类驱动程序将JDBC翻译成ODBC,然后使用一个ODBC驱动程序与数据库进行通信
- 第二类驱动程序是由部分Java程序和部分本地代码组成的,用于与数据库的客户端API进行通信
- 第三类驱动程序是纯Java客户端类库,它使用一种与具体数据库无关的协议将数据库请求发送给服务器构件,然后该构件再将数据库请求翻译成数据库相关的协议
- 第四类驱动程序是纯Java类库,它将JDBC请求直接翻译成数据库相关的协议
二、通过JDBC操作数据库
我们需要访问数据库时,首先要加载数据库驱动,只需加载一次,然后在每次访问数据库时创建一个Connection实例,获取数据库连接,获取连接后,执行需要的SQL语句,最后完成数据库操作时释放与数据库间的连接
1. 加载数据库驱动
Java加载数据库驱动的方法是调用Class类的静态方法forName(),语法格式如下:
Class.forName(StringdriverManager)
例如加载MySQL数据库驱动如下:
try { Class.forName("com.mysql.jdbc.Driver"); } catch(ClassNotFoundExceptione) { e.printStackTrace(); }
如果加载成功,会将加载的驱动类注册给DriverManager;如果加载失败,会抛出ClassNotFoundException异常。需要注意的是,要在项目中导入mysq-connection-java的jar包,方法是在项目中建立lib目录,在其下放入jar包。
右键jar包 Build Path->Add to Build Path
之后会多出一个Referenced Libraries,导入成功
2. 建立连接
加载完数据库驱动后,就可以建立数据库的连接了,需要使用DriverManager类的静态方法getConnection()方法来实现。如下:
Class.forName("com.mysql.jdbc.Driver");
Stringurl="jdbc:mysql://localhost:3306/database_name";
Stringuser="root";
Strignpassword="root"
//建立连接
Connectionconn=DriverManager.getConnection(url, user, password);
url是数据库的url,其中mysql指定数据库为mysql数据库,localhost是本地计算机,可以换成IP地址127.0.0.1,3306为MySQL数据库的默认端口号,database_name是所要连接的数据库名;user和password对应数据库的用户名和密码;最后再通过getConnection建立连接。
3. 对数据库表中数据进行增删改查
建立了连接之后,就可以使用Connection接口的createStatement()方法来获取Statement对象,也可以调用prepareStatement()方法获得PrepareStatement对象,通过executeUpdate()方法来执行SQL语句。
三、完整实例
下面给一个完整的例子,该例子的数据库配置文件在外部的properties中,该例子以SQL Server为例,其它的数据库都是同样的道理
1. jdbc.properties
用于编写数据库配置文件,不直接写在程序中的好处是提高了灵活性,如果需要修改数据库名称或配置等信息,可以在这里修改,无需改动程序
1driver=com.microsoft.sqlserver.jdbc.SQLServerDriver2url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=TTMS3username=root4password=rootimportjava.io.*; importjava.sql.Connection; importjava.sql.DriverManager; importjava.sql.PreparedStatement; importjava.sql.ResultSet; importjava.sql.SQLException; importjava.sql.Statement; importjava.util.Properties; publicclassDBUtil { privatefinalStringdbConnFile="resource/database/jdbc.properties"; privateConnectionconn=null; privateStringdbDriver; //定义驱动 privateStringdbURL; //定义URL privateStringuserName; //定义用户名 privateStringpassword; //定义密码 //从配置文件取数据库链接参数 privatevoidloadConnProperties(){ Propertiesprops=newProperties(); try { props.load(newFileInputStream(dbConnFile));//根据配置文件路径Conf加载配置文件 } catch (FileNotFoundExceptione) { e.printStackTrace(); } catch (IOExceptione) { e.printStackTrace(); } this.dbDriver=props.getProperty("driver");//从配置文件中取得相应的参数并设置类变量 this.dbURL=props.getProperty("url"); this.userName=props.getProperty("username"); this.password=props.getProperty("password"); } publicbooleanopenConnection(){ try { loadConnProperties(); Class.forName(dbDriver); this.conn=DriverManager.getConnection(dbURL,userName,password); returntrue; } catch(ClassNotFoundExceptionclassnotfoundexception) { classnotfoundexception.printStackTrace(); System.err.println("db: "+classnotfoundexception.getMessage()); } catch(SQLExceptionsqlexception) { System.err.println("db.getconn(): "+sqlexception.getMessage()); } returnfalse; } protectedvoidfinalize() throwsException{ try { if(null!=conn) conn.close(); }catch (SQLExceptione) { e.printStackTrace(); } } // 查询并得到结果集publicResultSetexecQuery(Stringsql) throwsException { ResultSetrstSet=null; try { if (null==conn) thrownewException("Database not connected!"); Statementstmt=conn.createStatement(); rstSet=stmt.executeQuery(sql); } catch (SQLExceptione) { e.printStackTrace(); } returnrstSet; } // 插入一条新纪录,并获取标识列的值publicResultSetgetInsertObjectIDs(StringinsertSql) throwsException{ ResultSetrst=null; try { if(null==conn) thrownewException("Database not connected!"); Statementstmt=conn.createStatement(); stmt.executeUpdate(insertSql, Statement.RETURN_GENERATED_KEYS); rst=stmt.getGeneratedKeys(); } catch (SQLExceptione) { e.printStackTrace(); } returnrst; } //以参数SQL模式插入新纪录,并获取标识列的值publicResultSetgetInsertObjectIDs(StringinsertSql, Object[] params) throwsException { ResultSetrst=null; PreparedStatementpstmt=null ; try { if (null==conn) thrownewException("Database not connected!"); pstmt=conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS); if(null!=params){ for (inti=0; i<params.length; i++) { pstmt.setObject(i+1, params[i]); } } pstmt.executeUpdate(); rst=pstmt.getGeneratedKeys(); } catch (SQLExceptione) { e.printStackTrace(); } returnrst; } // 插入、更新、删除publicintexecCommand(Stringsql) throwsException{ intflag=0; try { if(null==conn) thrownewException("Database not connected!"); Statementstmt=conn.createStatement(); flag=stmt.executeUpdate(sql); stmt.close(); } catch (SQLExceptione) { e.printStackTrace(); } returnflag; } /* // 存储过程调用public void callStordProc(String sql, Object[] inParams, SqlParameter[] outParams) throws Exception {CallableStatement cst = null ;try {if (null == conn)throw new Exception("Database not connected!");cst = conn.prepareCall(sql);if(null != inParams){ for (int i = 0; i < inParams.length; i++) { cst.setObject(i + 1, inParams[i]); } }if (null!=outParams){for (int i = 0; i < inParams.length; i++) {cst.registerOutParameter(outParams[i].getName(), outParams[i].getType()); } }cst.execute();} catch (SQLException e) {e.printStackTrace();}}*/// 释放资源publicvoidclose(ResultSetrst) throwsException { try { Statementstmt=rst.getStatement(); rst.close(); stmt.close(); } catch (SQLExceptione) { e.printStackTrace(); } } publicPreparedStatementexecPrepared(Stringpsql) throwsException { PreparedStatementpstmt=null ; try { if (null==conn) thrownewException("Database not connected!"); pstmt=conn.prepareStatement(psql); } catch (SQLExceptione) { e.printStackTrace(); } returnpstmt; } // 释放资源publicvoidclose(Statementstmt) throwsException { try { stmt.close(); } catch (SQLExceptione) { e.printStackTrace(); } } // 释放资源publicvoidclose() throwsSQLException, Exception{ if(null!=conn){ conn.close(); conn=null; } } publicConnectiongetConn() { returnconn; } publicstaticvoidmain(String[] args) { } }