JDBC 数据库连接

1. 第三种方式是最推荐的!

/**
 * 注意1.url中连接的数据库必须存在,比如hello必须存在,否则报错
 * 2.user 和password是固定的,不能写成username 或 pass,否则报错
 * @author ckang
 *
 */
public class JDBCDemo {
	
	private String url = "jdbc:mysql://localhost:3306/hello";
	String user = "root";
	String password = "root";
	
	@Test
	public void connectDB1() throws Exception{
		Properties props = new Properties();
		props.setProperty("user", user);
		props.setProperty("password", password);
		
		Driver driver = new com.mysql.jdbc.Driver();
		Connection connect = driver.connect(url, props);
		System.out.println(connect);
	}
	
	@Test
	public void connectDB2() throws Exception{
		//1.注册数据库驱动,可是mysql oracle sqlserver
		Driver mysqlDriver = new Driver();
		DriverManager.registerDriver(mysqlDriver);//可以注册多个不同的数据库
		//2.创建连接
		Connection connection = DriverManager.getConnection(url,user,password);//加入hello有密码和账号,此处不写就会报错
		System.out.println(connection);
	}
	@Test
	public void connectDB3() throws Exception{
		//1.注册数据库驱动程序,通过字节码来加载类信息,因为DriverManager.registerDriver都是静态方法
		Class.forName("com.mysql.jdbc.Driver");//加载mysql的驱动类Driver
		//2.创建连接
		Connection connection = DriverManager.getConnection(url, user, password);
		System.out.println(connection);
	}	
}

  2. 创建表, 通过statement 执行固定的sql, 一般先在数据库先测试sql语句

/**
 * CREATE TABLE student (id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), gender VARCHAR(2))
	DESC student
	DROP TABLE student
 * @author ckang
 *
 */

public class CreateDemo {
	private String url ="jdbc:mysql://127.0.0.1:3306/hello";
	private String user = "root";
	private String password = "root";
	
	@Test
	public void create() throws Exception{
		Statement stmt = null;
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url,user,password);
			stmt = conn.createStatement();
			String sql = "CREATE TABLE student (id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), gender VARCHAR(2))";
			stmt.execute(sql);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}finally{
			if(stmt != null){
				stmt.close();
			}
			if(conn != null){
				conn.close();
			}
		}
	}
}

  3.抽取公用类,抽取释放资源和获取连接的方法

public class JDBCUtils {
    private static String url = "jdbc:mysql://localhost:3306/hello";
    private static String user = "root";
    private static String password = "root";
    
    private JDBCUtils(){}
    
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");//1.注册驱动程序
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    //2. 获取数据库的连接的方法
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    //3.释放资源的方法
    public static void close(Statement stmt , Connection conn){
        if(null != stmt) {
            try {
                stmt.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if(null != conn) {
            try {
                conn.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}

4. 曾删改查方法

public class SaveOrUpdate {
	@Test
	public void save(){
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = JDBCUtils.getConnection();
			stmt = conn.createStatement();
			String sql = "insert into student(name,gender)values('波多野结衣妹子','女')";
			int count = stmt.executeUpdate(sql);
			System.out.println(count);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			JDBCUtils.close(stmt, conn);
		}
	}
	
	//注意:1. update table student报错,只能写update student!!!!  
	//如:"UPDATE student SET NAME='瑶瑶', gender='女' WHERE id = '2' AND NAME='zhangsan'"
	//2. set多个值时候只能用逗号隔开不能用and隔开!!!!
	@Test
	public void update(){
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = JDBCUtils.getConnection();
			stmt = conn.createStatement();
			String sql = "UPDATE student SET NAME='我爱瑶瑶', gender='女' WHERE id =2";
			stmt.executeUpdate(sql);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			JDBCUtils.close(stmt, conn);
		}
	}
	
	@Test
	public void delete(){
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = JDBCUtils.getConnection();
			stmt = conn.createStatement();
			String sql = "delete from student WHERE id =2";
			stmt.executeUpdate(sql);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			JDBCUtils.close(stmt, conn);
		}
	}
	
	public List<Student> findAll(){
		Connection conn = null;
		Statement stmt = null;
		
		try {
			conn = JDBCUtils.getConnection();
			stmt = conn.createStatement();
			String sql = "SELECT * FROM STUDENT";
			ResultSet resultSet = stmt.executeQuery(sql);
			List<Student> studentList = new ArrayList<>();
			while(resultSet.next()){
				Student student = new Student();
				student.setId(resultSet.getInt("id"));//列名必须与数据库的字段一样但不区分大小写
				student.setName(resultSet.getString("NAME"));
				student.setGender(resultSet.getString("GeNdEr"));
				studentList.add(student);
			}
			return studentList;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Test
	public void iterate(){
		List<Student> studentList = findAll();
		for(Student stu : studentList){
			System.out.println(stu.getId()+"***"+stu.getName()+"****"+stu.getGender());
		}
	}
}

	class Student{
		private int id;
		private String name;
		private String gender;
		
		public Student() {}
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getGender() {
			return gender;
		}
		public void setGender(String gender) {
			this.gender = gender;
		}
		@Override
		public String toString() {
			return "Student [id=" + id + ", name=" + name + ", gender="
					+ gender + "]";
		}
	}

  

posted @ 2016-09-19 23:55  黑土白云  阅读(214)  评论(0编辑  收藏  举报