JDBC

概要:数据库连接,数据库操作,代码规范化

平台及工具:mysql,eclipse ,jdk8

连接驱动:

win32位:http://pan.baidu.com/s/1c00fZ7i

ubunut : http://pan.baidu.com/s/1c0Ap1NM

(记得导入)

连接:

    private final static String url = "jdbc:mysql://localhost:3306/test";
    private final static String driver = "com.mysql.jdbc.Driver";
    private final static String user = "root",password= "******";

  Calss.forName(driver);

    Connection con =null;

  con = DriverManger.getConnection(url,user,password);

  测试连接是否成功 : 判断con 是否为空

操作:

主要的是用Statement 对象,将SQL语句注入到数据库

对于简单的语句,用Statement对象,对于IN参数的用PreparedStatement 对象,而CallableStatement对象处理带OUT参数的.

下面分别介绍:

  1.对于简单的,用Statement.

  String sql = "select * from where id="+id;                 //数据库的查询语句

  Statement st = con.createStatement();                  //通过con连接获得语句对象

  ResultSet rt = st.executeQurey(sql);                    //获得查询的结果

  st.close();rt.close();con.close();                      //释放

  (在使用Statement 对象中的方法之前应该先处理rt ,不然,将丢失查询的内容)    

  通过rt.getInt("字段值")获得当前查到的条目的信息,还有类似的getString("字段值")

  2.对于带IN参数的语句,用PreparedStatement对处理.

  String sql = "insert into 表名(字段1,字段2,....)" values(?,?,.......); //数据库的插入语句

  PreparedStatement pst = (PreparedStatement)con.PreparedStatement(sql); //创建对象

  pst.setInt(1,123);

  pst.setString(2,"asd");

  .

  .....

  pst.executeUpdate();      //更新 ,或提交

  pst.close();

  3.略(以后补充)

代码规范化:

代码规范化主要是:

  异常规范化处理,而不是简单的throws.

  操作规范化(简便) 将一些经常用到的代码写到一个类里面(定义成静态)(封装),以后如果用到,就可以直接导入调用

            避免重复写熟的不能再熟的代码(当然,一开始还是要自己动手的,优秀的程序员都这样做).

这里,可以数据库的一个表抽象成一个类,将对数据库的操作抽象成一个接口(当然还是要实现的,不然怎么用呢),包括增删查修等操作.同时这里也将对数据库驱动加载,连接,释放,都封装在了一个类里面了.

博客贴代码,短的话,是为了方便观看;长的话就有点装了,那稍稍装一下吧^_^! 

简单的操作也就这么多了.呵呵

最下面有源码地址

DBOperator

 1 package cn.hpu.jdbc.util;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 //import com.mysql.jdbc.Statement;
 8 import  java.sql.Statement;;
 9 
10 public class DBOperator {
11     private final static String url = "jdbc:mysql://localhost:3306/test";
12     private final static String driver = "com.mysql.jdbc.Driver";
13     private final static String user = "root",password= "******";//* 表示你自己的密码
14     
15     static {
16         try {
17             Class.forName(driver);
18         } catch (ClassNotFoundException e) {
19             // TODO Auto-generated catch block
20             System.out.println("驱动加载异常!");
21             e.printStackTrace();
22         }
23     }///加载一次驱动
24     
25     public static Connection getConnection(){
26         Connection con = null;
27         try {
28             con = DriverManager.getConnection(url,user,password);
29         } catch (SQLException e) {
30             // TODO Auto-generated catch block
31             System.out.println("连接数据库异常!");
32             e.printStackTrace();
33         }
34         return con;
35     }
36     
37     public static void close(ResultSet rt,Statement st,Connection con){
38         try{
39                 if(rt!=null) rt.close();
40                 if(st!=null)   st.close();
41                 if(con!=null) con.close();
42         }catch(Exception e){
43             e.printStackTrace();
44         }
45     }
46     
47     public static void close(Statement st, Connection conn)
48     {
49         close(null,st,conn);
50     }
51 }

StuManger 接口

 1 package cn.hpu.jdbc.serve;
 2 
 3 import cn.hpu.jdbc.model.Studnet;
 4 
 5 public interface StuManger {
 6     
 7     public  boolean  add(Studnet stu);
 8     public boolean del(int id );
 9     public boolean update(Studnet stu);
10     public Studnet qur(int id );
11     
12 }

接口实现

  1 package cn.hpu.jdbc.serve;
  2 import java.sql.Connection;
  3 
  4 import java.sql.ResultSet;
  5 
  6 import cn.hpu.jdbc.model.Studnet;
  7 import cn.hpu.jdbc.util.DBOperator;
  8 
  9 import com.mysql.jdbc.PreparedStatement;
 10 import com.mysql.jdbc.Statement;;
 11 
 12 public class StuMangerImplement implements StuManger{
 13     
 14     private Studnet stu;
 15 
 16     @Override
 17     public boolean add(Studnet stu) {
 18         // TODO Auto-generated method stub
 19         
 20         String sql=null;
 21         PreparedStatement pst = null ;
 22 
 23         boolean flag = false ;
 24         Connection conn = null ;
 25         try {
 26             conn = DBOperator.getConnection();
 27             sql = "insert into stu (id ,name,tel ) values(?,?,?)";
 28             pst = (PreparedStatement) conn.prepareStatement(sql);
 29             pst.setLong(1, stu.getId());
 30             pst.setString(2, stu.getName());
 31             pst.setString(3,stu.getTel());
 32             int row =pst.executeUpdate();
 33             if(row >0) flag=true;
 34             
 35         } catch (Exception e) {
 36             // TODO: handle exception
 37             e.printStackTrace();
 38         }finally {
 39             DBOperator.close((Statement) pst, conn);
 40         }
 41         return flag;
 42     }
 43 
 44     @Override
 45     public boolean del(int id) {
 46         // TODO Auto-generated method stub
 47         boolean flag = false ;
 48         PreparedStatement pst =null;
 49         Connection conn =null ;
 50         String sql=null;
 51         
 52         try {
 53             conn = DBOperator.getConnection();
 54             sql = "delete from stu where id=?";
 55             pst = (PreparedStatement) conn.prepareStatement(sql);
 56             pst.setLong(1, id);
 57             
 58             int rows = pst.executeUpdate();
 59             if(rows>0) flag=true ;
 60             
 61         } catch (Exception e) {
 62             // TODO: handle exception
 63             e.printStackTrace();
 64         }finally {
 65             DBOperator.close( pst, conn);
 66         }
 67         
 68         return flag;
 69     }
 70 
 71     @Override
 72     public boolean update(Studnet stu) {
 73         // TODO Auto-generated method stub
 74         boolean flag=false ;
 75         PreparedStatement pst = null;
 76         Connection conn = null;
 77         String sql =null;
 78         
 79         try {
 80             conn = DBOperator.getConnection();
 81             sql = "update stu set tel=?,name=? where id=? ";
 82             pst = (PreparedStatement) conn.prepareStatement(sql);
 83             pst.setString(1,stu.getTel());
 84             pst.setString(2, stu.getName());
 85             pst.setLong(3, stu.getId());
 86             int row = pst.executeUpdate();
 87             if(row > 0)
 88                 flag =true ;
 89         } catch (Exception e) {
 90             // TODO: handle exception
 91             e.printStackTrace();
 92         }finally{
 93             DBOperator.close(pst, conn);
 94         }
 95         return flag;
 96     }
 97 
 98     @Override
 99     public Studnet qur(int id) {
100         
101 //        boolean flag=false ;
102         java.sql.Statement st = null;
103         Connection conn = null;
104         String sql =null;
105         ResultSet rt = null;
106         stu = new Studnet();
107         try {
108             conn = DBOperator.getConnection();
109             sql = "select  * from stu where id="+id;
110             st=conn.createStatement();
111             rt = st.executeQuery(sql);        
112             if(rt.next())
113             {
114                 stu.setId(rt.getInt("id"));
115                 stu.setName(rt.getString("name"));
116                 stu.setTel(rt.getString("tel"));
117             }//
118             
119         } catch (Exception e) {
120             // TODO: handle exception
121             e.printStackTrace();
122         }finally{
123             DBOperator.close(st, conn);
124         }
125         return stu ;
126     }//返回特定id的学生的信息
127 
128 }

还有学生的信息的类及测试类,就不多贴了

相关源码:http://pan.baidu.com/s/1jG8brX8

原文地址:https://www.cnblogs.com/hpulfc/p/4665727.html