1. 程式人生 > >jdbc 程式設計

jdbc 程式設計

概念先參考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

 

 

待補充。。。。。。