Java代码与mysql数据库的连接

第一步建立一个JdbcMysqlpool类


public class JdbcMysqlpool {
	static{
		try {
			// 动态引入数据库驱动类
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public Connection getConnection(){
		Connection con =null;
		String url = "jdbc:mysql://192.168.13.21/java6?useUnicode=true&characterEncoding=utf-8&useSSL=false";
		String user = "user01";
		String password = "Password1!";
		try {
			// 发起连接
			con = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}
}

第二部建立一个JdbcConnectionTest测试类


public class JdbcConnectionTest {
	public static void main(String[] args){
		JdbcMysqlpool jdbc = new JdbcMysqlpool();
		
		Connection con = jdbc.getConnection();
		try {
			System.out.println(con.isClosed());
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(con!=null)
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}


你可能感兴趣的:(Java代码与mysql数据库的连接)