JDBC(Oracle資料庫為例)
阿新 • • 發佈:2018-11-21
1:建立表:
2:在Eclipse中Build Path
在Oracle資料庫安裝目錄:F:\sqldeveloper\jdbc\lib 下有個jar包,將它複製出來用於構建路徑。
3:操作資料庫(增刪改查)
package cn.JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import org.junit.Test; public class CDUS { //查詢資料 @Test public void test() throws Exception{ //記載驅動器 Class.forName("oracle.jdbc.OracleDriver"); //建立連線,連結資料庫 String url="jdbc:oracle:thin:@192.168.0.64:1521/xe"; // 連結 --驅動程式管理器 . 獲取連結 Connection con=DriverManager.getConnection(url,"lxl","1234"); //建立執行SQL語句的執行物件 //宣告 Statement st=con.createStatement(); //結果集 ResultSet rs=st.executeQuery("select * from stud"); //遍歷,輸出各項 while(rs.next()){ String id=rs.getString("id"); String name =rs.getString("name"); int age=rs.getInt("age"); String sex=rs.getString("sex"); System.err.println(id+","+name+","+age+","+sex); } //關閉 rs.close(); st.close(); con.close(); } //插入資料 @Test public void test1() throws Exception{ Class.forName("oracle.jdbc.OracleDriver"); String url="jdbc:oracle:thin:@192.168.0.64:1521/xe"; Connection con=DriverManager.getConnection(url,"lxl","1234"); Statement st=con.createStatement(); String sql="insert into stud(id,name,age,sex) values('S99','趙七',45,'F')"; int i=st.executeUpdate(sql); System.err.println("影響的行數"+i); st.close(); con.close(); } //刪除資料 @Test public void test2() throws Exception{ Class.forName("oracle.jdbc.OracleDriver"); String url="jdbc:oracle:thin:@192.168.0.64:1521/xe"; Connection con=DriverManager.getConnection(url,"lxl","1234"); Statement st=con.createStatement(); String sql="delete from stud where id='S99'"; int i=st.executeUpdate(sql); System.err.println("刪除的行數:"+i); st.close(); con.close(); } //修改資料 @Test public void test3() throws Exception{ Class.forName("oracle.jdbc.OracleDriver"); String url="jdbc:oracle:thin:@192.168.0.64:1521/xe"; Connection con=DriverManager.getConnection(url,"lxl","1234"); Statement st=con.createStatement(); String sql="update stud set name='王五' where id='S001'"; int i=st.executeUpdate(sql); System.err.println("修改的行數:"+i); st.close(); con.close(); } }