1. 程式人生 > >【Java基礎知識】JDBC基本操作

【Java基礎知識】JDBC基本操作

Jdbc簡介

JDBC(Java Data Base Connectivity )(java 資料庫連線)

可以為多種資料庫提供統一的資料庫訪問。


JDBC使用詳解

JDBC程式設計步驟

1.      載入驅動程式:Class.forName(driverClass)

載入Mysql驅動Class.forName(“com.mysql.jdbc.Driver”);

載入Oracle驅動:Class.forName(“oracle.jdbc.driver.OracleDriver”);

2.      獲得資料庫連線

DriverManager.getConnection(“jdbc:mysql://127.0.0.1:3306/imooc”,”root”,”root”);

3.      建立Statement物件:conn.createStatement();

例子:簡單MVC模式資料庫操作


1.首先建立我們的資料庫。

CREATE TABLE `imooc_goddess` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(30) NOT NULL,
  `sex` int(11) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  `email` varchar(30) DEFAULT NULL,
  `mobile` varchar(11) DEFAULT NULL,
  `create_user` varchar(30) DEFAULT NULL,
  `create_date` date DEFAULT NULL,
  `update_user` varchar(30) DEFAULT NULL,
  `update_date` date DEFAULT NULL,
  `isdel` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
2. 模型層M:Godness.java 類,和資料庫欄位相對應
/*
 * 模型層,建立類對應我們的資料庫
 */
public class Godness {
	private Integer id;
	private String user_name;
	private Integer sex;
	private Integer age;
	private Date birthday;
	private String email;
	private String mobile;
	private String create_user;
	private String update_user;
	private Date create_date;
	private Date update_date;
	private Integer isdel;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUser_name() {
		return user_name;
	}
	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}
	public Integer getSex() {
		return sex;
	}
	public void setSex(Integer sex) {
		this.sex = sex;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getCreate_user() {
		return create_user;
	}
	public void setCreate_user(String create_user) {
		this.create_user = create_user;
	}
	public String getUpdate_user() {
		return update_user;
	}
	public void setUpdate_user(String update_user) {
		this.update_user = update_user;
	}
	public Date getCreate_date() {
		return create_date;
	}
	public void setCreate_date(Date create_date) {
		this.create_date = create_date;
	}
	public Date getUpdate_date() {
		return update_date;
	}
	public void setUpdate_date(Date update_date) {
		this.update_date = update_date;
	}
	public Integer getIsdel() {
		return isdel;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public void setIsdel(Integer isdel) {
		this.isdel = isdel;
	}
	@Override
	public String toString() {
		return "Godness [id=" + id + ", user_name=" + user_name + ", sex="
				+ sex + ", age=" + age + ", birthday=" + birthday + ", email="
				+ email + ", mobile=" + mobile + ", create_user=" + create_user
				+ ", update_user=" + update_user + ", create_date="
				+ create_date + ", update_date=" + update_date + ", isdel="
				+ isdel + "]";
	}
}
3.模型層M:DBUtil.java 獲取資料庫的連線
public class DBUtil {

	private static final String URL = "jdbc:mysql://127.0.0.1:3306/jdbcdb";
	private static final String USER = "root";
	private static final String PASSWORD = "limeng";

	private static Connection conn = null;
	static {
		// 1.載入驅動程式
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// 2.獲得資料庫連線
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		return conn;
	}
}
4.模型層M:GodnessDao.java 增刪改查方法。
//增刪改查方法
public class GodnessDao {
	public void addGodness(Godness godness) throws SQLException{
		Connection conn = DBUtil.getConnection();
		String sql = ""+
				"insert into imooc_goddess"+
				"(user_name,sex,age,birthday,email,mobile,"+
				"create_user,create_date,update_user,update_date,isdel)"+
				"values("+
				"?,?,?,?,?,?,?,current_date(),?,current_date(),?)";
		//預編譯sql語句
		PreparedStatement ptmt = conn.prepareStatement(sql);
		
		ptmt.setString(1, godness.getUser_name());
		ptmt.setInt(2, 1);
		ptmt.setInt(3, godness.getAge());
		ptmt.setDate(4, new Date(godness.getBirthday().getTime()));
		ptmt.setString(5, godness.getEmail());
		ptmt.setString(6, godness.getMobile());
		ptmt.setString(7, godness.getCreate_user());
		ptmt.setString(8, godness.getUpdate_user());
		ptmt.setInt(9, 0);
		ptmt.execute();
	}
	
	public void updateGodness(Godness godness) throws SQLException{
		Connection conn = DBUtil.getConnection();
		String sql = ""+
				" update imooc_goddess"+
				" set user_name=?,sex=?,age=?,birthday=?,email=?,mobile=?,"+
				" create_user=?,update_user=?,update_date=current_date(),isdel=?"+
				" where id=?";
		//預編譯sql語句
		PreparedStatement ptmt = conn.prepareStatement(sql);
		
		ptmt.setString(1, godness.getUser_name());
		ptmt.setInt(2, 1);
		ptmt.setInt(3, godness.getAge());
		ptmt.setDate(4, new Date(godness.getBirthday().getTime()));
		ptmt.setString(5, godness.getEmail());
		ptmt.setString(6, godness.getMobile());
		ptmt.setString(7, godness.getCreate_user());
		ptmt.setString(8, godness.getUpdate_user());
		ptmt.setInt(9, 0);
		ptmt.setInt(10, godness.getId());
		ptmt.execute();
	}
	
	public void delGoddness(Integer id) throws SQLException{
		Connection conn = DBUtil.getConnection();
		String sql = ""+
				" delete from imooc_goddess"+
				" where id=?";
		//預編譯sql語句
		PreparedStatement ptmt = conn.prepareStatement(sql);
		
		ptmt.setInt(1, id);
		ptmt.execute();
	}
	//查詢所有的資料
	public List<Godness> query() throws SQLException{
		Connection conn = DBUtil.getConnection();
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery("select * from imooc_goddess");
		
		List<Godness> gs = new ArrayList<Godness>();
		Godness g = null;
		while (rs.next()) {
			g = new Godness();
			g.setId(rs.getInt("id"));
			g.setUser_name(rs.getString("user_name"));
			g.setAge(rs.getInt("age"));
			g.setSex(rs.getInt("sex"));
			g.setBirthday(rs.getDate("birthday"));
			g.setEmail(rs.getString("email"));
			g.setMobile(rs.getString("mobile"));
			g.setCreate_date(rs.getDate("create_date"));
			g.setCreate_user(rs.getString("create_user"));
			g.setUpdate_date(rs.getDate("update_date"));
			g.setUpdate_user(rs.getString("update_user"));
			g.setIsdel(rs.getInt("isdel"));
			gs.add(g);
		}
		return gs;
	}
	//根據姓名進行查詢
	public List<Godness> query(String name,String mobile,String email) throws SQLException{
		List<Godness> result = new ArrayList<Godness>();
		
		Connection conn = DBUtil.getConnection();
		StringBuilder sb = new StringBuilder();
		sb.append("select * from imooc_goddess ");
		sb.append(" where user_name like ? and mobile like ? and email like ?");
		
		PreparedStatement ptmt = conn.prepareStatement(sb.toString());
		ptmt.setString(1, "%"+name+"%");
		ptmt.setString(2, "%"+mobile+"%");
		ptmt.setString(3, "%"+email+"%");
		ResultSet rs = ptmt.executeQuery();
		Godness g = null;
		while (rs.next()) {
			g = new Godness();
			g.setId(rs.getInt("id"));
			g.setUser_name(rs.getString("user_name"));
			g.setAge(rs.getInt("age"));
			g.setSex(rs.getInt("sex"));
			g.setBirthday(rs.getDate("birthday"));
			g.setEmail(rs.getString("email"));
			g.setMobile(rs.getString("mobile"));
			g.setCreate_date(rs.getDate("create_date"));
			g.setCreate_user(rs.getString("create_user"));
			g.setUpdate_date(rs.getDate("update_date"));
			g.setUpdate_user(rs.getString("update_user"));
			g.setIsdel(rs.getInt("isdel"));
			result.add(g);
		}
		return result;
	}
	
	public List<Godness> query(List<Map<String,Object >> params) throws SQLException{
		List<Godness> result = new ArrayList<Godness>();
		
		Connection conn = DBUtil.getConnection();
		StringBuilder sb = new StringBuilder();
		sb.append("select * from imooc_goddess where 1=1 ");
		
		
		if(params != null && params.size()>0){
			for(int i = 0; i<params.size();i++){
				Map<String, Object> map = params.get(i);
				sb.append(" and "+map.get("name")+" "+map.get("rela")+" "+map.get("value"));
			}
		}
		
		PreparedStatement ptmt = conn.prepareStatement(sb.toString());
		ResultSet rs = ptmt.executeQuery();
		Godness g = null;
		while (rs.next()) {
			g = new Godness();
			g.setId(rs.getInt("id"));
			g.setUser_name(rs.getString("user_name"));
			g.setAge(rs.getInt("age"));
			g.setSex(rs.getInt("sex"));
			g.setBirthday(rs.getDate("birthday"));
			g.setEmail(rs.getString("email"));
			g.setMobile(rs.getString("mobile"));
			g.setCreate_date(rs.getDate("create_date"));
			g.setCreate_user(rs.getString("create_user"));
			g.setUpdate_date(rs.getDate("update_date"));
			g.setUpdate_user(rs.getString("update_user"));
			g.setIsdel(rs.getInt("isdel"));
			result.add(g);
		}
		return result;
	}
	
	public Godness get(Integer id) throws SQLException{
		Connection conn = DBUtil.getConnection();
		String sql = ""+
				" select * from imooc_goddess"+
				" where id=?";
		//預編譯sql語句
		PreparedStatement ptmt = conn.prepareStatement(sql);
		
		ptmt.setInt(1, id);
		ResultSet rs =ptmt.executeQuery();
		Godness g = new Godness();
		while(rs.next()){
			g = new Godness();
			g.setId(rs.getInt("id"));
			g.setUser_name(rs.getString("user_name"));
			g.setAge(rs.getInt("age"));
			g.setSex(rs.getInt("sex"));
			g.setBirthday(rs.getDate("birthday"));
			g.setEmail(rs.getString("email"));
			g.setMobile(rs.getString("mobile"));
			g.setCreate_date(rs.getDate("create_date"));
			g.setCreate_user(rs.getString("create_user"));
			g.setUpdate_date(rs.getDate("update_date"));
			g.setUpdate_user(rs.getString("update_user"));
			g.setIsdel(rs.getInt("isdel"));
		}
		return g;
	}
}
5.控制層C: GodnessAction.java 呼叫模型層的方法
//控制層
public class GodnessAction {
	
	public void add(Godness godness) throws SQLException{
		GodnessDao dao = new GodnessDao();
		dao.addGodness(godness);
	}
	
	public Godness get(Integer id) throws SQLException{
		GodnessDao dao = new GodnessDao();
		return dao.get(id);
	}
	
	public void edit(Godness godness) throws SQLException{
		GodnessDao dao = new GodnessDao();
		dao.updateGodness(godness);
	}
	
	public void del(Integer id) throws SQLException{
		GodnessDao dao = new GodnessDao();
		dao.delGoddness(id);
	}
	
	public List<Godness> query() throws SQLException{
		GodnessDao dao= new GodnessDao();
		return dao.query();
	}
	
	public List<Godness> query(List<Map<String,Object >> params) throws SQLException{
		GodnessDao dao = new GodnessDao();
		return dao.query(params);
	}
}
6.檢視層V: View.java 和使用者進行資料互動。
public class View {
	private static final String CONTEXT = "歡迎來到女神禁區:\n" + "功能列表:\n"
			+ "[MAIN/M]:主選單\n" + "[QUERY/Q]:檢視全部女神的資訊\n"
			+ "[GET/G]:檢視某位女神的詳細資訊\n" + "[ADD/A]:新增女神資訊\n"
			+ "[UPDATE/U]:更新女神資訊\n" + "[DELETE/D]:刪除女神資訊\n"
			+ "[SEARCH/S]:查詢女神資訊(根據姓名、手機號來查詢)\n" + "[EXIT/E]:退出女神禁區\n"
			+ "[BREAK/B]:退出當前功能,返回主選單";
	private static final String OPERATION_MAIN = "MAIN";
	private static final String OPERATION_QUERY = "QUERY";
	private static final String OPERATION_GET = "GET";
	private static final String OPERATION_ADD = "ADD";
	private static final String OPERATION_UPDATE = "UPDATE";
	private static final String OPERATION_DELETE = "DELETE";
	private static final String OPERATION_SEARCH = "SEARCH";
	private static final String OPERATION_EXIT = "EXIT";
	private static final String OPERATION_BREAK = "BREAK";

	public static void main(String[] args) {
		System.out.println(CONTEXT);

		Scanner scanner = new Scanner(System.in);
		Godness godness = new Godness();
		GodnessAction action = new GodnessAction();
		String prenious = null;
		Integer step=1;
		List<Map<String, Object>> params = new ArrayList<Map<String,Object>>();
		while (scanner.hasNext()) {
			String in = scanner.next().toString();
			if (OPERATION_EXIT.equals(in.toUpperCase())
					|| OPERATION_EXIT.substring(0, 1).equals(in.toUpperCase())) {
				System.out.println("你已退出");
				break;
			}else if (OPERATION_MAIN.equals(in.toUpperCase())
					|| OPERATION_MAIN.substring(0, 1).equals(in.toUpperCase())
					||OPERATION_BREAK.equals(in.toUpperCase())
					||OPERATION_BREAK.substring(0, 1).equals(in.toUpperCase())){
					System.out.println(CONTEXT);
			}else if (OPERATION_SEARCH.equals(in.toUpperCase())
					|| OPERATION_SEARCH.substring(0, 1).equals(in.toUpperCase())
					|| OPERATION_SEARCH.equals(prenious)) {
					//根據姓名和電話號碼查詢
					prenious = OPERATION_SEARCH;
					if(step ==1){
						
						System.out.println("請輸入女神的[姓名]");
						
					}else if(step ==2){
						Map<String, Object> p = new HashMap<String, Object>();
						p.put("name", "user_name");
						p.put("rela", "=");
						p.put("value","'"+in+"'");
						params.add(p);
						System.out.println("請輸入女神的[電話]");
					}else if(step == 3){
						Map<String, Object> p = new HashMap<String, Object>();
						p.put("name", "mobile");
						p.put("rela", "=");
						p.put("value", "'"+in+"'");
						params.add(p);
						try {
							List<Godness> res = action.query(params);
							for(Godness g:res){
								System.out.println(g.getId() + " , " + g.getUser_name()
										+ " , " + g.getSex() + "," + g.getAge() + ","
										+ g.getBirthday() + "," + g.getEmail() + ","
										+ g.getMobile() + "," + g.getIsdel());
							}
							step = 1;
							prenious = null;
							params.clear();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
					if(OPERATION_SEARCH == prenious){
						step ++;
					}
			}else if (OPERATION_UPDATE.equals(in.toUpperCase())
					|| OPERATION_UPDATE.substring(0, 1).equals(in.toUpperCase())
					|| OPERATION_UPDATE.equals(prenious)) {
				prenious = OPERATION_UPDATE;
				// 更新女神
				if(1==step){
					System.out.println("請輸入要修改女神的[id]:");
				}else if(2==step){
					godness.setId(Integer.valueOf(in));
					System.out.println("請輸入女神[姓名]");
				}else if(3 == step){
					godness.setUser_name(in);
					System.out.println("請輸入女神[年齡]");
				}else if(4 == step){
					godness.setAge(Integer.valueOf(in));
					System.out.println("請輸入女神[生日],格式如:yyyy-MM-dd");
				}else if(5 == step){
					SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
					Date birthday = null;
					try{
						birthday = sf.parse(in);
						godness.setBirthday(birthday);
						System.out.println("請輸入女神[郵箱]");
					}catch(ParseException e){
						e.printStackTrace();
						System.out.println("你輸入的格式有誤,請重新輸入");
						step = 3;
					}
				}else if(6 == step){
					godness.setEmail(in);
					System.out.println("請輸入女神的[手機號]");
				}else if(7==step){
					godness.setMobile(in);
					try{
						action.edit(godness);
						System.out.println("更新女神成功");
						step = 1;
						prenious = null;
					}catch(Exception e){
						e.printStackTrace();
						System.out.println("更新女神失敗");
					}
				}
				
				if(OPERATION_UPDATE.equals(prenious)){
					step++;
				}
			}else if (OPERATION_DELETE.equals(in.toUpperCase())
					|| OPERATION_DELETE.substring(0, 1).equals(in.toUpperCase())
					|| OPERATION_DELETE.equals(prenious)) {
					prenious = OPERATION_DELETE;
					if(step == 1){
						step ++;
						System.out.println("刪除女神資訊,請輸入ID:");
					}else{
						try {
							action.del(Integer.valueOf(in));
							System.out.println("刪除成功!");
						} catch (NumberFormatException e) {
							e.printStackTrace();
						} catch (SQLException e) {
							e.printStackTrace();
						}
						step --;
						prenious = null;
					}
			}else if (OPERATION_GET.equals(in.toUpperCase())
					|| OPERATION_GET.substring(0, 1).equals(in.toUpperCase())
					|| OPERATION_GET.equals(prenious)) {
				prenious = OPERATION_GET;
				if(step == 1){
					step ++;
					System.out.println("獲取女神的詳細資訊,請輸入ID:");
				}else{
					try {
						Godness godness2 = action.get(Integer.valueOf(in));
						System.out.println(godness2.getId() + " , " + godness2.getUser_name()
								+ " , " + godness2.getSex() + "," + godness2.getAge() + ","
								+ godness2.getBirthday() + "," + godness2.getEmail() + ","
								+ godness2.getMobile() + "," + godness2.getIsdel());
					} catch (NumberFormatException e) {
						e.printStackTrace();
					} catch (SQLException e) {
						e.printStackTrace();
					}
					step --;
					prenious = null;
				}
			}else if (OPERATION_QUERY.equals(in.toUpperCase())
					|| OPERATION_QUERY.substring(0, 1).equals(in.toUpperCase())) {
				try {
					List<Godness> list = action.query();
					for(Godness go : list){
						System.out.println(go.getId() +" --姓名:"+go.getUser_name());
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if (OPERATION_ADD.equals(in.toUpperCase())
					|| OPERATION_ADD.substring(0, 1).equals(in.toUpperCase())
					|| OPERATION_ADD.equals(prenious)) {
				prenious = OPERATION_ADD;
				// 新增女神
				if(1==step){
					System.out.println("請輸入女神[姓名]");
					
				}else if(2 == step){
					godness.setUser_name(in);
					System.out.println("請輸入女神[年齡]");
				}else if(3 == step){
					godness.setAge(Integer.valueOf(in));
					System.out.println("請輸入女神[生日],格式如:yyyy-MM-dd");
				}else if(4 == step){
					SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
					Date birthday = null;
					try{
						birthday = sf.parse(in);
						godness.setBirthday(birthday);
						System.out.println("請輸入女神[郵箱]");
					}catch(ParseException e){
						e.printStackTrace();
						System.out.println("你輸入的格式有誤,請重新輸入");
						step = 3;
					}
				}else if(5 == step){
					godness.setEmail(in);
					System.out.println("請輸入女神的[手機號]");
				}else if(6==step){
					godness.setMobile(in);
					try{
						action.add(godness);
						System.out.println("新增女神成功");
						step = 1;
						prenious = null;
					}catch(Exception e){
						e.printStackTrace();
						System.out.println("新增女神失敗");
					}
				}
				if(OPERATION_ADD.equals(prenious)){
					step++;
				}
				
			} else {
				System.out.println("你輸入的值為:" + in);
			}

		}
	}
}
慕課網視訊連結:http://www.imooc.com/learn/157