jdbc 編程
阿新 • • 發佈:2019-01-08
nal exe rda host connect rim strong .html prop
概念先參考:https://www.cnblogs.com/wuziyue/p/4827295.html
不要問為什麽,直接代碼搞起
1. com.domain 包 User 實體類
package com.domain; public class User { private String u_name; private int u_age; public String getU_name() { return u_name; } public void setU_name(String u_name) { this.u_name = u_name; } public int getU_age() { return u_age; } public void setU_age(int u_age) { this.u_age = u_age; } public User() { } public User(String u_name, int u_age) { super(); this.u_name = u_name; this.u_age = u_age; } @Override public String toString() { return "User [u_name=" + u_name + ", u_age=" + u_age + "]"; } }
2. com.dao 包下的 IUserDao 接口
package com.dao; import java.util.List; import com.domain.User; public interface IUserDao { void addUserInfo(User user); void deleteUserInfo(User user); void updateUserAgeInfo(User user,int age); User selectUserInfoByName(String name); List<User> selectAllUserInfo(); }
3. com.dao.impl 包 UserDaoImpl 類
package com.dao.impl; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.Util.JDBCUtil; import com.dao.IUserDao; import com.domain.User; public class UserDaoImpl implements IUserDao{ ResultSet rs = null; Statement st = null; User user = null; /*常見的異常錯誤:No operations allowed after connection closed. 因為 當 數據庫的連接Connection是一個Static的,程序共享這一個Connection。 那麽第一次對數據庫操作沒問題,當把Connection關閉後,第二次還想操作數據庫時Connection肯定不存在了。 所以為了解決這個問題:我們最好把 創建Connection的實例寫到每個操作的方法中。 */ /* 1. 增加用戶信息*/ @Test public void addUserInfo(User user){ Connection conn = JDBCUtil.getInstance().getConnection(); try { st = conn.createStatement(); int row = st.executeUpdate("insert into tb_user (id,`name`,age)values(null,‘"+user.getU_name()+"‘,"+user.getU_age()+")"); if(row > 0){ System.out.println("添加用戶成功"); } } catch (SQLException e) { e.printStackTrace(); } JDBCUtil.getInstance().closeAll(rs,st,conn); } /*2. 刪除用戶信息*/ @Test public void deleteUserInfo(User user) { Connection conn = JDBCUtil.getInstance().getConnection(); try{ st = conn.createStatement(); int row = st.executeUpdate("delete from tb_user where name = ‘"+user.getU_name()+"‘"); if(row > 0){ System.out.println("刪除用戶成功"); } }catch (Exception e) { e.printStackTrace(); } JDBCUtil.getInstance().closeAll(rs,st,conn); } /*3. 修改用戶信息*/ @Test public void updateUserAgeInfo(User user,int age) { Connection conn = JDBCUtil.getInstance().getConnection(); try{ st = conn.createStatement(); int row = st.executeUpdate("update tb_user set age = "+age+" where name = ‘"+user.getU_name()+"‘"); if(row > 0){ System.out.println("修改用戶信息成功"); } }catch (Exception e) { e.printStackTrace(); } JDBCUtil.getInstance().closeAll(rs,st,conn); } /*4. 通過name查詢一個用戶信息*/ @Test public User selectUserInfoByName(String name) { Connection conn = JDBCUtil.getInstance().getConnection(); //這裏如果不寫,當方法3中調用次方法時,就會因為 Connection 關閉而報錯。 try{ st = conn.createStatement(); rs = st.executeQuery("select * from tb_user where `name` = ‘"+name+"‘"); while(rs.next()){ user = new User(); user.setU_name(rs.getString("name")); user.setU_age(rs.getInt("age")); } }catch (Exception e) { e.printStackTrace(); } JDBCUtil.getInstance().closeAll(rs,st,conn); return user; } /*5. 查詢所有用戶信息*/ @Override public List<User> selectAllUserInfo() { Connection conn = JDBCUtil.getInstance().getConnection(); List<User> userlist = new ArrayList(); try{ st = conn.createStatement(); rs = st.executeQuery("select * from tb_user"); while(rs.next()){ User user = new User(); user.setU_name(rs.getString("name")); user.setU_age(rs.getInt("age")); userlist.add(user); } }catch (Exception e) { e.printStackTrace(); } JDBCUtil.getInstance().closeAll(rs,st,conn); return userlist; } }
4. com.Util 包 JDBCUtil 類 封裝共用的代碼
package com.Util; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCUtil { /*// 1. 參數是硬編碼在代碼中 private static String driverName = "com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/mysql001"; private static String userName = "root"; private static String passWorld = "root"; private static JDBCUtil instance = null; Connection conn; static{ try { Class.forName(driverName); instance = new JDBCUtil(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //獲得鏈接對象 public Connection getConn(){ try { return DriverManager.getConnection(url,userName,passWorld); } catch (SQLException e) { e.printStackTrace(); } return null; } //關閉鏈接資源 public void close(ResultSet rs, Statement st, Connection conn){ try { if(rs!=null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }finally { try { if(st!=null) st.close(); } catch (SQLException e) { e.printStackTrace(); }finally { try { if(conn!=null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } */ //2.把參數放到資源文件中 static Properties prop = new Properties(); //懶漢模式獲取 JDBCUtil類的一個實例 private JDBCUtil(){} private static JDBCUtil instance = null; public static JDBCUtil getInstance(){ if(instance == null){ instance = new JDBCUtil(); } return instance; } static{ try { prop.load(new FileInputStream("jdbc.properties")); Class.forName(prop.getProperty("driverName")); } catch (Exception e) { e.printStackTrace(); } } //獲得鏈接對象 public Connection getConnection(){ Connection conn = null; try { conn = DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("userName"),prop.getProperty("password")); } catch (SQLException e) { e.printStackTrace(); } return conn; } //關閉所有鏈接資源 public void closeAll(ResultSet rs, Statement st, Connection conn){ try { if(rs!=null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }finally { try { if(st!=null) st.close(); } catch (SQLException e) { e.printStackTrace(); }finally { try { if(conn!=null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
5. com.test 包 TestDao 測試類
package com.test; import java.util.List; import java.util.Scanner; import org.junit.Test; import com.dao.IUserDao; import com.dao.impl.UserDaoImpl; import com.domain.User; public class TestDao { IUserDao userdao = new UserDaoImpl(); @Test public void addUserInfo(){ User user = new User("趙本本",75); //獲取數據 userdao.addUserInfo(user); //將數據傳到Dao層進行數據庫操作 } @Test public void deleteUserInfo(){ User user = new User("趙本本",75); userdao.deleteUserInfo(user);; } /*修改用戶信息*/ @Test public void updateUserAgeInfo(){ System.out.println("請輸入要修改的用戶姓名:"); String name = new Scanner(System.in).nextLine(); //將name傳到dao層驗證該用戶是否存在 User user = userdao.selectUserInfoByName(name); if(user != null){ System.out.println("請輸入修改後的用戶年齡:"); int age = new Scanner(System.in).nextInt(); //將user對象和age傳到dao層進行修改數據操作 userdao.updateUserAgeInfo(user,age);; }else{ System.out.println("不存在該用戶,gameover!!"); } } @Test public void selectUserInfoByName(){ System.out.println("請輸入查詢的學生姓名"); String name = "李四"; System.out.println(userdao.selectUserInfoByName(name)); } @Test public void selectAllUserInfo(){ List<User> userlist = userdao.selectAllUserInfo(); for (User user : userlist) { System.out.println(user); } } }
6. 數據庫表:
CREATE TABLE `tb_user` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `age` int(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
7. jdbc.properties 配置文件
driverName = com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/mysql001 userName = root password = root
待補充。。。。。。
jdbc 編程