一文学会Java安装JDK

  • Post category:Java

以下是详细的Java安装JDK的方法,并且包含两条示例代码:

Java安装JDK

  1. 下载JDK安装包
  2. 首先访问Oracle官网的下载页面:https://www.oracle.com/java/technologies/javase-downloads.html
  3. 接着,在页面上选择你需要的JDK版本以及操作系统,并点击下载按钮进行下载

  4. 安装JDK

  5. 待下载完成后,直接双击安装包运行,按照提示进行安装即可
  6. 安装后,需要配置环境变量,将JDK加入到系统的PATH路径中,详情可参考官方文档:https://docs.oracle.com/en/java/javase/14/install/installation-jdk-microsoft-windows-platforms.html#GUID-54E76953-C8A0-4D37-A61E-D288368F4469

  7. 验证JDK是否正确安装

  8. 打开命令行或终端窗口,输入java -version命令
  9. 如果控制台输出了类似于以下信息,说明JDK已经成功安装并配置:

java version "11.0.7" 2020-04-14 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.7+8-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.7+8-LTS, mixed mode)

以上就是Java安装JDK的方法,示例代码如下:

// Java示例代码1:输出"Hello, World!"
public class HelloWorld {
   public static void main(String[] args) {
      System.out.println("Hello, World!");
   }
}
// Java示例代码2:使用JDBC连接MySQL数据库
import java.sql.*;

public class JdbcDemo {
   static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/EMP";
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
      Connection conn = null;
      Statement stmt = null;
      try{
         Class.forName(JDBC_DRIVER);

         System.out.println("Connecting to database...");
         conn = DriverManager.getConnection(DB_URL, USER, PASS);

         System.out.println("Creating statement...");
         stmt = conn.createStatement();
         String sql;
         sql = "SELECT id, first, last, age FROM Employees";
         ResultSet rs = stmt.executeQuery(sql);

         while(rs.next()){
            int id  = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            System.out.print("ID: " + id);
            System.out.print(", Age: " + age);
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
         }

         rs.close();
         stmt.close();
         conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }catch(Exception e){
         e.printStackTrace();
      }finally{
         try{
            if(stmt!=null)
               stmt.close();
         }catch(SQLException se2){
         }
         try{
            if(conn!=null)
               conn.close();
         }catch(SQLException se){
            se.printStackTrace();
         }
      }
      System.out.println("Goodbye!");
   }
}