1.jdbc的概述
是sun公司统一提供的一套接口规范,各个数据库生产商提供实现
注册驱动,获得连接,获得执行的SQL语句对象,释放资源
package com.learn.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.junit.Test; public class Demo1 { Connection conn = null; @Test public void test() { try { //注册驱动 Class.forName("com.mysql.jdbc.Driver"); //获得连接 String url = "jdbc:mysql///mydatebase"; String user = "root"; String password = "root"; conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); //释放资源 if( conn != null) { try { conn.close(); } catch (SQLException e1) { e1.printStackTrace(); } //垃圾回收尽快回收对象 conn = null; } } } }
2.JDBC的API
connection
statement
3.JDBC的元数据MataDate(提高通用性较高的代码)
- DatabaseMetaData:获得数据库连接的信息,获得数据库的表的信息.
* 获得数据库元数据:Connection中getMetaData();
- ParameterMetaData:获得SQL中的参数的个数及类型.
* 获得参数元数据:PreparedStatement中getParameterMetaData()
- ResultSetMetaData:获得结果集中的列名及列的类型.
* 获得结果集元数据:ResultSet中getMeta()
4.元数据的使用
public void demo2(){ Connection conn = null; conn = JDBCUtils2.getConnection(); // 获得数据库元数据: try { DatabaseMetaData metaData = conn.getMetaData(); System.out.println("获得驱动名称:"+metaData.getDriverName()); System.out.println("获得驱动URL:"+metaData.getURL()); System.out.println("获得用户名:"+metaData.getUserName()); // 获得表中的主键: ResultSet rs = metaData.getPrimaryKeys(null, null, "category"); if(rs.next()){ String name = rs.getString("COLUMN_NAME"); System.out.println(name); } } catch (SQLException e) { e.printStackTrace(); } }
参数元数据
public void demo3(){ Connection conn = null; PreparedStatement stmt = null; try{ conn = JDBCUtils2.getConnection(); String sql = "update category set cname = ? where cid = ?"; stmt = conn.prepareStatement(sql); ParameterMetaData metaData = stmt.getParameterMetaData(); int count = metaData.getParameterCount(); System.out.println(count); }catch(Exception e){ } }
结果集元数据
public void demo4(){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try{ conn = JDBCUtils2.getConnection(); String sql = "select * from category"; stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); ResultSetMetaData metaData = rs.getMetaData(); int count = metaData.getColumnCount(); for(int i = 1;i<=count ;i++){ String name = metaData.getColumnName(i); String type = metaData.getColumnTypeName(i); System.out.println(name+type); } }catch(Exception e){ } }