statement 的延伸 ----》PreparedStatement

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;


public class demo1 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Connection conn = null;
  PreparedStatement pstmt = null;
  
   String sql = "UPDATE dog SET name=?,heath=?,love=? WHERE id=?";
  try {


   //加载数据库驱动
   
   Class.forName("com.mysql.jdbc.Driver");
   
   conn = DriverManager.getConnection("jdbc:mysql:///epet","root","root");
   
   pstmt = conn.prepareStatement(sql);
   
   pstmt.setString(1, "xiaoguo"); //括号中1指的是  sql中的name     2指的是 修改的参数
   pstmt.setInt(2, 12);
   pstmt.setInt(3, 15);
   pstmt.setInt(4, 2);
   
   pstmt.executeUpdate();
   System.out.println("成功");
   
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }finally{
   try {
    
    if (null != pstmt) {
     pstmt.close();
    }
    if (null != conn) {
     conn.close();
    }
   } catch (Exception e2) {
    // TODO: handle exception
   }
   
  }
  
  
 }

}

posted @ 2016-12-14 09:14  蚂蚁偏偏爱上树  阅读(158)  评论(0编辑  收藏  举报