package com.bjsxt;
import java.sql.*;
public class JdbcTest {
//	向Departments表中添加一条数据
    public void insertDepartments(String department_name,int location_id) {
    	   Connection conn = null;
    	   Statement state = null;
    	try {
    		//驱动注册
    		Class.forName("com.mysql.jdbc.Driver");
    		//创建连接
    		conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjsxt?useUnicode=true&characterEncoding=utf-8","root","root");
    		//通过Statement 执行sql语句
    		String sql = "insert into departments values(default,'"+department_name+"',"+location_id+")";
    		state = conn.createStatement();
    		int flag = state.executeUpdate(sql);
    		System.out.println(flag);
    	}catch(Exception e) {
    		e.printStackTrace();
    	}finally {
    		if(state != null) {
    			try {
					state.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    		if(conn != null) {
    			try {
					conn.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    	}
    }
//    更新department表中的department_id 为6的数据 修改名称名为教学部,location_id = 6
    public void updateDepartments(String department_name,int location_id,int department_id) {
    	Connection conn = null;
    	Statement state = null;
    	try {
    		Class.forName("com.mysql.jdbc.Driver");
    		conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjsxt?useUnicode=true&characterEncoding=utf-8","root","root");
    		state = conn.createStatement();
    		String sql2 = "update departments d set d.department_name = '" +department_name+"',d.location_id"+location_id+"where d.department_id = "+department_id;
    		int flag2 = state.executeUpdate(sql2);
    	}catch(Exception e) {
    		e.printStackTrace();
    	}finally {
    		if(state != null) {
    			try {
					state.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    		if(conn != null) {
    			try {
					conn.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    		
    	}
    }
    public static void main(String[] args) {
    	JdbcTest test = new JdbcTest();
//    	test.insertDepartments("劳斯莱斯", 4);
    	test.updateDepartments("兰博基益",4,7);
    }
}
捕获.JPG