java-JDBC操作數據庫
阿新 • • 發佈:2017-12-18
ava 安裝 oracle cond con eat sele png set
通過JDBC操作數據庫。
1. 準備jar包,做為驅動。如下圖。
2. 需要安裝數據庫(我這裏使用的數據庫為Oracle),保證數據庫開啟。
正式進入數據庫操作:
只有一個簡單的 TestDB類:
1 package testJDBC; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 importView Codejava.sql.Statement; 9 10 public class TestDB { 11 public static void main(String[] args) throws ClassNotFoundException, SQLException{ 12 13 String url = "jdbc:oracle:thin:@localhost:1521:orcl"; 14 String username = "scott"; 15 String password = "drew324"; 16 17//first 18 Class.forName("oracle.jdbc.driver.OracleDriver"); 19 20 //second 21 String sql = "select * from emp"; 22 Connection connection = DriverManager.getConnection(url,username,password); 23 24 //third 25 //Statement pstmt = connection.createStatement();26 PreparedStatement pstmt = connection.prepareStatement(sql); 27 28 //forth 29 //ResultSet resultSet = pstmt.executeQuery(sql); 30 ResultSet resultSet = pstmt.executeQuery(); 31 32 //fifth 33 while(resultSet.next()) { 34 System.out.println(resultSet.getInt(1)); 35 } 36 37 //sixth 38 resultSet.close(); 39 pstmt.close(); 40 connection.close(); 41 } 42 43 }
java-JDBC操作數據庫