java連線資料庫和執行靜態和動態的sql語句
阿新 • • 發佈:2019-01-09
►JDBC (Java DatabaseConnectivity) 是用於執行SQL 語句的Java 應用程式介面,由一組用Java 語言編寫的類和介面組成。
►JDBC 是一種規範,各資料庫廠商為Java 程式設計師提供標準的資料庫訪問類和介面,使得獨立於DBMS 的Java 應用程式的開發工具和產品成為可能。
►其官方網站為:http://java.sun.com/products/jdbc/index.jsp。
oracle資料庫的驅動:oracle.jdbc.oracleDriver
oracle的url:jdbc:oracle:thin:@localhost:1521:安裝資料庫時的別名 一般都是orcl
mysql資料庫的驅動:com.mysql.jdbc.Driver
oracle的url:jdbc:mysql://localhost:3306/資料庫名
連線資料庫案例
獲取Connection物件
第一種
第二種 封裝一個工具類來獲取Connection物件 建立一個 資原始檔====== properties檔案 以oracle為例
測試類1(執行動態的sql語句)
預編譯SQL語句:PreparedStatement pscolumn=conn.prepareStatement(sql);
Connection conn=DriverManager.getConnection(url, name, paw);
Class.forName("資料的驅動");
第二種 封裝一個工具類來獲取Connection物件 建立一個 資原始檔====== properties檔案 以oracle為例
url=jdbc:oracle:thin:@localhost:1521:orcl
driverClass=oracle.jdbc.OracleDriver
username=scott
password=tiger
建立一個工具類 可以獲取connection物件測試類(執行靜態的sql語句) Statement st=conn.createStatement() 獲取執行靜態sqlpackage cn.et; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; public class OracleDbUtil { static Properties p=new Properties(); static{ //讀取資原始檔 InputStream is=OracleDbUtil.class.getResourceAsStream("/oracle.properties"); try { //將properties檔案的鍵值對載入到記憶體中 p.load(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection() throws Exception{ String url=p.getProperty("url");//獲取連線伺服器的ip地址 埠 和資料庫 String driverClass=p.getProperty("driverClass");//告訴jdbc使用的是什麼資料庫 String uname=p.getProperty("username");//使用哪個賬號登入 String pwd=p.getProperty("password");//登入密碼 Class.forName(driverClass);//載入該類 Connection conn=DriverManager.getConnection(url,uname,pwd);//獲取連線資料庫的物件 return conn; } }
package jdbcCURD;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import java.sql.DatabaseMetaData;
public class MysqlCURD {
public static void main(String[] args) throws Exception {
}
//查詢
@Test
public void select() throws Exception{
Connection conn=MysqlDbUtils.getConnection();
Statement st=conn.createStatement();
//Statement用於執行靜態的sql語句
ResultSet re=st.executeQuery("select * from dept");
//ResultSet遊標遍歷資料行 next()
while(re.next()){
String deptno=re.getString("deptno");//通過列明獲取資料
String dname=re.getString("dname");
String loc=re.getString(3);//通過索引獲取資料
System.out.println(deptno+"--"+dname+"--"+loc);
}
st.close();
conn.close();
}
//增加
@Test
public void insert() throws Exception{
Connection conn=MysqlDbUtils.getConnection();
Statement st=conn.createStatement();
int re=st.executeUpdate("insert into teacher values(5,'老廖')");
System.out.println(re);
st.close();
conn.close();
}
//刪除
@Test
public void delete() throws Exception{
Connection conn=MysqlDbUtils.getConnection();
Statement st=conn.createStatement();
int re=st.executeUpdate("delete from teacher where t=5");
System.out.println(re);
st.close();
conn.close();
}
//修改
@Test
public void update() throws Exception{
Connection conn=MysqlDbUtils.getConnection();
Statement st=conn.createStatement();
int re=st.executeUpdate("update teacher set tname='廖廖' where t=5");
System.out.println(re);
st.close();
conn.close();
}
}
測試類1(執行動態的sql語句)
預編譯SQL語句:PreparedStatement pscolumn=conn.prepareStatement(sql);
package cn.et;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test_2 {
/*
* 3 寫出一個分頁的方法
* 定義如下
* tablePager(tableName,curPage,pageSize)
* 呼叫
* tablePager('Emp',2,10)
* 查詢emp表中 第二頁的資料(每頁顯示10條 第二頁就是 10-20條)
* 5
*
* 1 1--5 curPage*pageSize-(pageSize-1) curPage*pageSize
* 2 6---10 curPage*pageSize-oageSize*1+1=pageSize*(curPage-1)+1
* 3 11---15
*
*
*/
public static void main(String[] args) throws Exception {
tablePager("EMP",1,100);
}
public static void tablePager(String tableName,int curPage,int pageSize) throws Exception{
int start=pageSize*(curPage-1)+1;
int end=curPage*pageSize;
//連線資料庫
Connection conn=OracleDbutil.getConnection();
//獲取所有的列明
String count="select wm_concat(column_name) from user_tab_cols where table_name=?";
//System.out.println(count);
//預編譯獲取所有的列明語句
PreparedStatement pscolumn=conn.prepareStatement(count);
//設值
pscolumn.setString(1,tableName);
//遊標抓取資料
ResultSet rs=pscolumn.executeQuery();
rs.next();
//獲取一行資料
String column=rs.getString(1);
//按逗號分隔 把所有的列名放在s陣列中
String[] s=column.split(",");
//分頁查詢語句
String sql="select "+column+" from (select t.*,rownum rn from "+tableName+" t) where rn>=? and rn<=?";
//System.out.println(sql);
//預編譯分頁查詢語句
PreparedStatement ps=conn.prepareStatement(sql);
//設值
ps.setInt(1,start);
ps.setInt(2, end);
//遊標抓取資料
ResultSet rt=ps.executeQuery();
while(rt.next()){
//遍歷陣列可以獲取下標
for(int i=1;i<=s.length;i++){
System.out.print(rt.getString(i)+" ");
}
System.out.println();
}
}
}
測試類2(動態sql語句)
package cn.et;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/*定義一個儲存過程 傳入表名
刪除該表中的重複記錄
比如 deleteMul(tableName)
呼叫 deleteMul('emp'); 必須刪除表emp的重複資料 (execute immediate using )*/
public class Test_3 {
public static void main(String[] args) throws Exception {
deleteMul("EMP");
}
public static void deleteMul(String tableName) throws Exception{
//連線資料庫
Connection cn=OracleDbutil.getConnection();
//獲取列明語句
String count="select wm_concat(column_name) from user_tab_cols where table_name=?";
//預編譯獲取列明語句
PreparedStatement pscount=cn.prepareStatement(count);
//設值
pscount.setString(1, tableName);
//獲取所有的列明
ResultSet rs=pscount.executeQuery();
rs.next();//必須呼叫該方法
String columns=rs.getString(1);
System.out.println(columns);
//刪除重複記錄語句
String delete="delete from "+tableName+" where rowid not in (select min(rowid) from "+tableName+" group by "+columns+ ")";
System.out.println(delete);
Statement stat=cn.createStatement();
stat.executeQuery(delete);
//關閉連線
stat.close();
rs.close();
pscount.close();
cn.close();
}
}