Java JDBC和多線程是Java編程中非常重要的兩個概念,下面將分別介紹它們的基本概念和用法。
Java JDBC是Java提供的連接各種關系型數據庫的API,可以通過Java JDBC連接數據庫并執行各種數據庫操作語句。
import java.sql.*; public class JDBCTest { public static void main(String[] args) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); String sql = "select * from users"; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { System.out.println(rs.getString("name") + " " + rs.getInt("age")); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
多線程是Java編程中用于提高程序并發性和響應速度的重要工具。
public class ThreadTest { public static void main(String[] args) { Thread thread1 = new Thread(new PrintThread(1)); Thread thread2 = new Thread(new PrintThread(2)); thread1.start(); thread2.start(); } static class PrintThread implements Runnable { private int id; public PrintThread(int id) { this.id = id; } @Override public void run() { for (int i = 0; i< 10; i++) { System.out.println("Thread " + id + " count " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
以上就是Java JDBC和多線程的基本介紹和使用方法。