MyEclipse連接mySql數據庫筆記


  1. 連接數據庫測試代碼
     1 package com.imooc.db;
     2 
     3 import java.sql.DriverManager;
     4 import java.sql.ResultSet;
     5 import java.sql.Statement;
     6 
     7 //import com.mysql.jdbc.Connection;
     8 import java.sql.Connection;;
     9 
    10 public class DBUtil {
    11     private static final String URL ="jdbc:mysql://localhost:3306/imooc";
    12     private static final String USER = "root";
    13     private static final String PASSWORD = "yy550432";
    14     public static void main(String[] args) throws Exception {
    15         
    16         //加載驅動程序
    17         Class.forName("com.mysql.jdbc.Driver");
    18         //獲得數據庫的連接
    19         Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
    20         //操縱數據庫,實現增刪改查
    21         Statement stmt=conn.createStatement();
    22         ResultSet rs=stmt.executeQuery("select user_name from imooc_goddess");
    23         while(rs.next()) {
    24             System.out.println(rs.getString("user_name"));
    25         }        
    26     }
    27 }
    28     
  2. 創建模型層:1)根據數據庫的內容寫一個數據類,類中的成員變量與數據庫數據對應,2)一個對數據類對象進行增刪改查的事件類,對數據庫數據進行操作。數據庫的操作是通過數據庫連接來進行的,通過傳遞的方式將數據庫連接引入到事件類中。
                    
    數據類:
     1 package com.imooc.model;
     2 
     3 import java.util.Date;
     4 
     5 public class Goddess {
     6     private Integer id;
     7     private String user_name;
     8 
     9     private Date create_date;
    10     private Integer sex;
    11     private Integer isdel;
    12     public String getuser_name() {
    13         return user_name;
    14     }
    15     
    16     public void setuser_name(String user_name) {
    17         this.user_name = user_name;
    18     }
    19     
    20     public Integer getIsdel() {
    21         return isdel;
    22     }
    23     
    24     public void setIsdel(Integer isdel) {
    25         this.isdel = isdel;
    26     }
    27 
    28     public Integer getId() {
    29         return id;
    30     }
    31 
    32     public void setId(Integer idInteger) {
    33         this.id = idInteger;
    34     }
    35 
    36     public Date getCreate_date() {
    37         return create_date;
    38     }
    39 
    40     public void setCreate_date(Date create_date) {
    41         this.create_date = create_date;
    42     }
    43 
    44     public Integer getSex() {
    45         return sex;
    46     }
    47 
    48     public void setSex(Integer sexString) {
    49         this.sex = sexString;
    50     }
    51 
    52     @Override
    53     public String toString() {
    54         return "Goddess [id=" + id + ", user_name=" + user_name + ", create_date=" + create_date + ", sex=" + sex
    55                 + ", isdel=" + isdel + "]";
    56     }
    57     
    58     
    59 
    60 }

    事件類:

      1 package com.imooc.dao;
      2 
      3 import java.sql.Connection;
      4 import java.sql.Date;
      5 import java.sql.PreparedStatement;
      6 import java.sql.ResultSet;
      7 import java.sql.SQLException;
      8 import java.sql.Statement;
      9 import java.util.ArrayList;
     10 import java.util.List;
     11 import java.util.Map;
     12 
     13 import com.imooc.db.DBUtil;
     14 import com.imooc.model.Goddess;
     15 
     16 public class goddessDao {
     17     /**
     18      * 增加女神信息
     19      * @param g要增加的女神對象
     20      * @throws Exception
     21      */
     22     public  void addGoddess(Goddess g) throws Exception {
     23         //獲得數據庫連接
     24         Connection conn = DBUtil.getConnection();
     25         //拼寫sql語句
     26         String sqlString ="insert into imooc_goddess"
     27                             +"(user_name,sex,create_date)"
     28                             +"values(?,?,?)";//占位符,在下面的Sql語句預編譯的時候把參數傳進去
     29         //預編譯sql語句
     30         PreparedStatement ptmy = conn.prepareStatement(sqlString);
     31         //傳參,為預編譯符賦值
     32         ptmy.setString(1, g.getuser_name());
     33         ptmy.setInt(2, g.getSex());
     34         ptmy.setDate(3, new Date(g.getCreate_date().getTime()));
     35         //執行
     36         ptmy.execute();
     37     }
     38 
     39     /**
     40      * 更新女神信息
     41      * @param g要更新的女神對象
     42      * @throws Exception
     43      */
     44     public void updateGoddess(Goddess g) throws Exception {
     45         //獲得數據庫連接
     46         Connection conn = DBUtil.getConnection();
     47         //拼寫sql語句
     48         String sqlString =""+
     49                             " update imooc_goddess"+
     50                             " set user_name=?,sex=?,create_date=?"+
     51                             " where id=?";
     52                             //占位符,在下面的Sql語句預編譯的時候把參數傳進去
     53         //預編譯sql語句
     54         PreparedStatement ptmy = conn.prepareStatement(sqlString);
     55         //傳參,為預編譯符賦值
     56         ptmy.setString(1, g.getuser_name());
     57         ptmy.setInt(2, g.getSex());
     58         ptmy.setDate(3, new Date(g.getCreate_date().getTime()));
     59         ptmy.setInt(4, g.getId());
     60         //執行
     61         ptmy.execute();
     62         
     63     }
     64     
     65     /**
     66      * 刪除女神信息
     67      * @param g要刪除的女神對象
     68      * @throws Exception
     69      */
     70     public void deGoddess(Integer id) throws Exception {
     71         //獲得數據庫連接
     72         Connection conn = DBUtil.getConnection();
     73         //拼寫sql語句
     74         String sqlString =""+
     75                             " delete from imooc_goddess"+
     76                             " where id = ?";
     77                             //占位符,在下面的Sql語句預編譯的時候把參數傳進去
     78         //預編譯sql語句
     79         PreparedStatement ptmy = conn.prepareStatement(sqlString);
     80         //傳參,為預編譯符賦值
     81         ptmy.setInt(1, id);
     82 
     83         //執行
     84         ptmy.execute();
     85         
     86     }
     87 
     88     /**
     89      * 根據id獲取單個女神對象
     90      * @param id
     91      * @return
     92      * @throws Exception
     93      */
     94     public Goddess getGoddess(Integer id) throws Exception {
     95         //Goddess g=null;
     96         Goddess g=new Goddess();
     97         //獲得數據庫連接
     98         Connection conn = DBUtil.getConnection();
     99         //拼寫sql語句
    100         String sqlString =""+
    101                             " select * from imooc_goddess"+
    102                             " where id=? ";
    103                             //占位符,在下面的Sql語句預編譯的時候把參數傳進去
    104         //預編譯sql語句
    105         PreparedStatement ptmy = conn.prepareStatement(sqlString);
    106         //傳參,為預編譯符賦值
    107         ptmy.setInt(1, id);
    108         //執行
    109         ResultSet rs=ptmy.executeQuery();
    110         while (rs.next()) {
    111             //g =new Goddess();
    112             g.setId(rs.getInt("id"));
    113             g.setSex(rs.getInt("sex"));
    114             g.setuser_name(rs.getString("user_name"));
    115             g.setCreate_date(rs.getDate("create_date"));
    116     }
    117         return g;
    118         
    119     }
    120     
    121     public List<Goddess> get(String name) throws Exception {
    122         List<Goddess> gs = new ArrayList<Goddess>();
    123         
    124         Connection conn = DBUtil.getConnection();
    125 //        // 操縱數據庫,實現增刪改查
    126 //        Statement stmt = conn.createStatement();    
    127 //        //沒有加過濾
    128 //        ResultSet rs = stmt.executeQuery("select user_name,sex from imooc_goddess");
    129         //多個查詢條件:select user_name,sex,create_date,id from imooc_goddess where user_name =? and id=?"
    130         //模糊查詢:
    131 //        "select user_name,sex,create_date,id from imooc_goddess where user_name like ?"
    132 //        ptmt.setString(1,"%"+name+%);
    133         //以姓名查詢:
    134         String sqlString = "select user_name,sex,create_date,id from imooc_goddess where user_name =?";
    135         //預編譯sql語句
    136         PreparedStatement ptmy = conn.prepareStatement(sqlString);
    137         //傳參,為預編譯符賦值
    138         ptmy.setString(1, name);
    139         //執行
    140         ResultSet rs=ptmy.executeQuery();
    141         
    142         Goddess g = null;    
    143         while (rs.next()) {    
    144             g = new Goddess();
    145             g.setSex(rs.getInt("sex"));
    146             g.setuser_name(rs.getString("user_name"));
    147             g.setCreate_date(rs.getDate("create_date"));
    148             g.setId(rs.getInt("id"));
    149             gs.add(g);        
    150         }
    151         return gs;    
    152     }
    153     
    154     /**
    155      * 將sql語句作為參數傳進來查詢(查詢的最終優化版本)
    156      * @param params 
    157      * @return 查詢出符合條件的結果集合
    158      * @throws Exception
    159      */
    160     
    161     public List<Goddess> get(List<Map<String, Object>> params) throws Exception {
    162         List<Goddess> gs = new ArrayList<Goddess>();
    163         
    164         Connection conn = DBUtil.getConnection();
    165 
    166         StringBuilder sBuilder =new StringBuilder();
    167         //小技巧
    168         sBuilder.append("select * from imooc_goddess where 1=1");
    169         if(params != null &&params.size()>0) {
    170             for (int i = 0; i < params.size(); i++) {
    171                 Map<String, Object> map=params.get(i);
    172                 sBuilder.append(" and "+map.get("name")+" "+map.get("rela")+" "+map.get("value"));
    173             }
    174         }
    175         PreparedStatement ptmtPreparedStatement  = conn.prepareStatement(sBuilder.toString());
    176         System.out.println(sBuilder.toString());
    177         //執行
    178         ResultSet rs=ptmtPreparedStatement.executeQuery();
    179         
    180         Goddess g = null;    
    181         while (rs.next()) {    
    182             g = new Goddess();
    183             g.setSex(rs.getInt("sex"));
    184             g.setuser_name(rs.getString("user_name"));
    185         //    g.setCreate_date(rs.getDate("create_date"));
    186             g.setCreate_date(rs.getDate("create_date"));
    187             g.setId(rs.getInt("id"));
    188 //            g.setIsdel(rs.getInt("isdel"));
    189             gs.add(g);        
    190 //            System.out.println(rs.getString("user_name"));
    191         }
    192         return gs;    
    193     }
    194     /**
    195      * 查詢女神信息(sql固定)
    196      * @return 結果集合
    197      * @throws Exception
    198      */
    199     public List<Goddess> get() throws Exception {
    200         List<Goddess> gs = new ArrayList<Goddess>();
    201         
    202         Connection conn = DBUtil.getConnection();
    203         // 操縱數據庫,實現增刪改查
    204         Statement stmt = conn.createStatement();    
    205         //沒有加過濾
    206         ResultSet rs = stmt.executeQuery("select user_name,sex from imooc_goddess ");
    207         
    208         Goddess g = null;    
    209         while (rs.next()) {    
    210             g = new Goddess();
    211             g.setSex(rs.getInt("sex"));
    212             g.setuser_name(rs.getString("user_name"));
    213             gs.add(g);
    214 //        
    215 //            System.out.println(rs.getString("user_name"));
    216         }
    217         return gs;
    218         
    219     }
    220 
    221 
    222 }

     

  3. 結果測試代碼:
     1 package com.imooc.action;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Date;
     5 import java.util.HashMap;
     6 import java.util.List;
     7 import java.util.Map;
     8 
     9 import com.imooc.dao.goddessDao;
    10 import com.imooc.model.Goddess;
    11 
    12 public class GoddessAction {
    13     public static void main(String[] args) throws Exception {
    14         goddessDao g = new goddessDao();
    15         List<Map<String, Object>> params= new ArrayList<Map<String,Object>>();
    16         Map<String, Object> param = new HashMap<String, Object>();
    17         param.put("name", "user_name");
    18         param.put("rela", "=");
    19         param.put("value", "'小四'");//注意此處要加一個單引號
    20         params.add(param);
    21         
    22         //模糊查詢
    23         param.put("name", "user_name");
    24         param.put("rela", "like");
    25         param.put("value", "'%小%'");
    26         params.add(param);
    27         
    28         
    29         List<Goddess> result = g.get(params); 
    30         for (int i = 0; i < result.size(); i++) {
    31             System.out.println(result.get(i).toString());    
    32         }
    33         
    34         
    35 //        goddessDao g = new goddessDao();
    36 //        List<Goddess> gs = g.get("小四");
    37 //        for (int i = 0; i < gs.size(); i++) {
    38 //            System.out.println(gs.get(i).toString());    
    39 //        }
    40 //        for (Goddess goddess : gs) {
    41 //                
    42 //        }
    43     
    44 //        goddessDao g = new goddessDao();
    45 //        Goddess gGoddess=new Goddess();        
    46 //        gGoddess.setuser_name("新小二");
    47 //        gGoddess.setSex(12);
    48 //        gGoddess.setCreate_date(new Date());
    49 //        gGoddess.setId(11);
    50         
    51 //        Goddess myGoddess =g.getGoddess(6);
    52 //        System.out.println(myGoddess.toString());
    53         
    54     //    g.deGoddess(2);
    55     //    g.updateGoddess(gGoddess);
    56     //    g.addGoddess(gGoddess);
    57         
    58     }
    59 
    60 }
  4. 控制層:接收視圖層參數,調用模型層,模型層  1 package com.imooc.action;
     2 
     3 import java.util.ArrayList;  4 import java.util.Date;  5 import java.util.HashMap;  6 import java.util.List;  7 import java.util.Map;  8 
     9 import com.imooc.dao.goddessDao;  10 import com.imooc.model.Goddess;  11 
     12 public class GoddessAction {  13     
     14     public void add(Goddess goddess) throws Exception {  15         goddessDao dao = new goddessDao();  16  dao.addGoddess(goddess);  17  }  18     
     19     public void update(Goddess goddess) throws Exception {  20         goddessDao dao = new goddessDao();  21  dao.updateGoddess(goddess);  22         
     23  }  24     public void del(Integer id) throws Exception {  25         goddessDao dao = new goddessDao();  26  dao.deGoddess(id);  27  }  28     
     29     public List<Goddess> query() throws Exception {  30         goddessDao dao = new goddessDao();  31         return dao.get();  32  }  33     
     34     public List<Goddess> query(List<Map<String, Object>> params) throws Exception {  35         goddessDao dao = new goddessDao();  36         return dao.get(params);  37  }  38     /**
     39  * 獲取單個女神  40  * @param id  41  * @return
     42  * @throws Exception  43      */
     44     public Goddess query(Integer id) throws Exception {  45         goddessDao dao = new goddessDao();  46         return dao.getGoddess(id);  47  }  48       
     54
     56 // public static void main(String[] args) throws Exception {  57 // goddessDao g = new goddessDao();  58 // List<Map<String, Object>> params= new ArrayList<Map<String,Object>>();  59 // Map<String, Object> param = new HashMap<String, Object>();  60 // param.put("name", "user_name");  61 // param.put("rela", "=");  62 // param.put("value", "'小四'");//注意此處要加一個單引號  63 // params.add(param);  64 //        
     65 //        //模糊查詢  66 // param.put("name", "user_name");  67 // param.put("rela", "like");  68 // param.put("value", "'%小%'");  69 // params.add(param);  70 //        
     71 //        
     72 // List<Goddess> result = g.get(params);  73 // for (int i = 0; i < result.size(); i++) {  74 // System.out.println(result.get(i).toString());  75 // }  76 //        
     77 //        
     78 //// goddessDao g = new goddessDao();
     79 //// List<Goddess> gs = g.get("小四");
     80 //// for (int i = 0; i < gs.size(); i++) {
     81 //// System.out.println(gs.get(i).toString()); 
     82 //// }
     83 //// for (Goddess goddess : gs) {
     84 ////                
     85 //// }  86 //    
     87 //// goddessDao g = new goddessDao();
     88 //// Goddess gGoddess=new Goddess(); 
     89 //// gGoddess.setuser_name("新小二");
     90 //// gGoddess.setSex(12);
     91 //// gGoddess.setCreate_date(new Date());
     92 //// gGoddess.setId(11);  93 //        
     94 //// Goddess myGoddess =g.getGoddess(6);
     95 //// System.out.println(myGoddess.toString());  96 //        
     97 //    // g.deGoddess(2);  98 //    // g.updateGoddess(gGoddess);  99 //    // g.addGoddess(gGoddess); 100 //        
    101 // }
    102 
    103 }

    控制層測試代碼:

     1 package com.imooc.test;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Date;
     5 import java.util.HashMap;
     6 import java.util.List;
     7 import java.util.Map;
     8 
     9 import com.imooc.action.GoddessAction;
    10 import com.imooc.dao.goddessDao;
    11 import com.imooc.model.Goddess;
    12 
    13 public class TestAction {
    14     public static void main(String[] args) throws Exception {
    15         GoddessAction goddessAction = new GoddessAction();
    16         //測試刪除
    17 //        goddessAction.del(10);
    18 //        
    19 ////測試查詢        
    20 //        List<Goddess> result= goddessAction.query(); 
    21 //        for (int i = 0; i < result.size(); i++) {
    22 //        System.out.println(result.get(i).toString());    
    23 //    }
    24 //測試更新        
    25 //        Goddess goddess = new Goddess();
    26 //        goddess.setId(1);
    27 //        goddess.setCreate_date(new Date());
    28 //        goddess.setuser_name("小十四");
    29 //        goddess.setSex(41);
    30 //        goddessAction.update(goddess);
    31         
    32         //測試傳參查詢    
    33         List<Map<String, Object>> params= new ArrayList<Map<String,Object>>();
    34         Map<String, Object> param = new HashMap<String, Object>();
    35         param.put("name", "user_name");
    36         param.put("rela", "=");
    37         param.put("value", "'小四'");//注意此處要加一個單引號
    38         params.add(param);
    39         
    40         //模糊查詢
    41         param.put("name", "user_name");
    42         param.put("rela", "like");
    43         param.put("value", "'%小%'");
    44         params.add(param);    
    45         
    46         List<Goddess> result = goddessAction.query(params); 
    47         for (int i = 0; i < result.size(); i++) {
    48             System.out.println(result.get(i).toString());    
    49         }
    50     }
    51 }

    5、視圖層


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM