JDBC(一)

  JDBC(Java DataBase Conectivity)Java数据库连接,是J2SE的一部分,由java.sql和javax.sql组成。

package dbTest;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class JDBCTest { 
    public static void main(String[] args) { 
        String driver = "com.mysql.jdbc.Driver"; 
        String dbName = "nnm5"; 
        String passwrod = "OSSDB123"; 
        String userName = "root"; 
        String url = "jdbc:mysql://localhost:13306/" + dbName; 
        String sql = "select ircnetnodeid, purpose_id,ircnetypeid from rcnetnode limit 1"; 
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
         
        try { 
            //注册驱动,只需要一次,可以注册多个driver
            Class.forName(driver);   //把类装载到虚拟机中,会去执行com.myql.jdbc.Driver中静态代码块进行注册
            //DriverManager.register(new com.mysql.jdbc.Driver());
            //System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver:com.oracle.jdbc.Driver");

            //JDBC获取连接
            Connection conn = DriverManager.getConnection(url, userName,passwrod); 

            ps = conn.prepareStatement(sql); 

            rs = ps.executeQuery(); 
            while (rs.next()) { 
                System.out.println("ircnetnodeid : " + rs.getObject("ircnetnodeid") + " purpose_id : "
                        + rs.getObject("purpose_id") + " ircnetypeid : " + rs.getObject("ircnetypeid")); 
            }   
        } catch (Exception e) { 
            e.printStackTrace(); 
        }finally{
      //需要注意关闭的顺序,链接资源一定要释放
            // 关闭记录集 
            if (rs != null) { 
                try { 
                    rs.close(); 
                } finally{
            if(ps != null){
               try{
                 ps.close();
                           }finally{
                if(conn != null){
                  conn.close();
                           }
                        }
            }
               }             
          }         
    }   
}    

     上面使用的是PreparedStatement而不是Statement,可以防止数据注入,在预编译时就报错,有参数时不应直接拼接字符串,而应该使用占位符(?)的形式。

  如果存在很多的查询,则像上面这样获取链接,释放链接会出现很多的重复代码,应该是做一个工具类,提供CRUD方法,只需要传递SQL语句和参数即可。利用Spring的JDBCTemplate可以很大程度上减少重复代码。     

public class DBConnectionManager{
  
  static{
   Class.forName("com.mysql.jdbc.Driver");
  }

 //读操作
 public static List<Map<String,Object>> selectObject(String sql, String[] params) throws Exception {
  Connection conn = null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  List<Map<String,Object>>> result  = new ArrayList<Map<String,Object>>>();
  try {
   conn = DBConnectionManager.getConnection();   
   pstmt = conn.prepareStatement(sql);
   
   for (int i = 0; params != null && i < params.length; i++) {
    pstmt.setString(i + 1, params[i]);
   }
   rs = pstmt.executeQuery();
   ResultSetMetaData meta = rs.getMetaData();
   while (rs.next()) {
    Map<String,Object> columnValue = new HashMap<String,Object>
    int size = meta.getColumnCount();
    for (int i = 1; i <= size; i++) {
     String columnName = meta.getColumnLabel(i);  //getColumnName返回的是数据库列名,getColumnLabel如有别名将返回列的别名,否则和getColumnName相同
columnValue.add(columnName,rs.getObject(columnName)); } result.add(columnValue); }
return result; } catch (Exception e) { //logger.info("Execute sql : " + sql + " fail!!!"); throw e; } finally { DBConnectionManager.free(conn, pstmt, rs); } } //增删改操作 public static void updateObject(String sql, String[] params) throws Exception { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DBConnectionManager.getConnection(); pstmt = conn.prepareStatement(sql); for (int i = 0; params != null && i < params.length; i++) { pstmt.setObject(i + 1, params[i]); } rs = pstmt.executeUpdate(); } catch (Exception e) { //logger.info("Execute sql : " + sql + " fail!!!"); throw e; } finally { DBConnectionManager.free(conn, pstmt, rs); } } //更好的做法是从数据库连接池中取链接 public static Connection getConnection(){ String dbName = "nnm5"; String passwrod = "OSSDB123"; String userName = "root"; String url = "jdbc:mysql://localhost:13306/" + dbName; Connection conn = DriverManager.getConnection(url, userName,passwrod); return conn; } public static void free(Connection conn,PreparedStatement pstmt,ResultSet rs){ if (rs != null) { try { rs.close(); } finally{          if(ps != null){            try{              ps.close(); }finally{              if(conn != null){                conn.close(); } }          } } } }

     Statement的方法是executeQuery(String sql),如果要使用PreparedStatement需要调用的方法是executeQuery(),这点是需要注意的。

     JDBCUtil中查询操作可以用executeQuery(),增加,删除,更新操作都可以用executeUpdate()。

 

     java.util.Date和java.sql.Date的关系是sql中的Date继承自util中的Date。ResultSet的getDate方法返回的是sql中的Date,做增加操作时需要传递的是sql包中的Date,不能是util中的Date,如果是就需要转换,这点是需要注意的。

     将util中的Date类型date转换为sql中的Date:new java.sql.Date(date.getTime());

     util中的Date既有日期又有时间,sql中的Date只有日期。

     

     varchar最多存储255个字符,数量再大时就需要clob类型。二进制对应的是blob类型。

     MySQL中的clob类型是text,blob类型就是blob(64个字节)或者mediumblob,longblob,使用时要注意最大的长度。   

   public void setBlob(){
      try{
          conn = DriverManager.getConnection(url, userName,passwrod); 
      
          String sql = "insert into blob_test(big_blob) values(?)";
          ps = conn.prepareStatement(sql); 
          File f = new File("src/pattern/decorator/a.jpeg")
          InputStream is = new BufferedInputStram(new FileInputStram(f));
          ps.setBinaryStream(1, is, (int)f.length);

          rs = ps.executeUpdate(); 
          is.close();
      }finally{
          JDBCUtil.free(rs, ps, conn);
      }
   }     

   public void getBlob(){
    conn = DriverManager.getConnection(url, userName,passwrod); 
      
    String sql = "select big_blob from blob_test where id = ?";
    ps = conn.prepareStatement(sql); 
    ps.setInteger(1,new Integer(1));
    rs = ps.executeQuery(); 
        
    while(rs.next()){
       int BYTE_SIZE = 1;
       int SAVE_SIZE = 1024;
       int i = 0;
       byte[] buff = new byte[BYTE_SIZE]; // 每次读的缓存
       byte[] save = new byte[SAVE_SIZE]; // 保存前缓存
       InputStream in = rs.getBinaryStream(1);
        
       FileOutputStream  fs = new FileOutputStream(new File("src/pattern/decorator/b.jpeg"));
       while (in.read(buff) != -1) { // 一个字节一个字节读
            save[i] = buff[0];
            if (i == SAVE_SIZE - 1) { // 达到保存长度时开始保存
               fs.write(save, 0, SAVE_SIZE);
               save = new byte[SAVE_SIZE];
               i = 0;
             } else {
               i++;           
             }                   
       }
       // 最后这段如果没达到保存长度,需要把前面的保存下来
       if (i > 0) {
           fs.write(save, 0, i);
       }           
       fs.close();
       bf.close();
    }
    JDBCUtil.free(rs, ps, conn);
}

 

 
posted on 2014-10-20 23:32  lnlvinso  阅读(377)  评论(0编辑  收藏  举报