1.JDBC操作mysql數(shù)據(jù)庫(kù)-增刪改查
//查詢數(shù)據(jù)
@Test
public void testQuery(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.注冊(cè)驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//2.獲取連接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
conn = DriverManager.getConnection(url, user, password);
//3.獲取執(zhí)行SQL的statement
stmt = conn.createStatement();
//4.執(zhí)行SQL
String sql = "select * from user";
stmt.execute(sql);
rs = stmt.getResultSet();
//5.處理結(jié)果
while(rs.next()){
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println("---------------");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//6.釋放資源
release(rs,stmt,conn);
}
}
//釋放資源
public static void release(ResultSet rs,Statement stmt,Connection conn){
//6.釋放資源
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stmt = null;
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
}
}
2.JDBC操作Oracle數(shù)據(jù)庫(kù)-增刪改查
public void exeCuteQuery()throws Exception{
Connection conn=null;
//1.加載驅(qū)動(dòng)
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.建立連接
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","C##yujun","123456");
//3.建立命令
Statement st=conn.createStatement();
//4.創(chuàng)建sql語(yǔ)句
String sql="select * from student order by stuid,score desc";
//執(zhí)行命令獲取結(jié)果集
ResultSet rs=st.executeQuery(sql);
System.out.println("姓名\t科目\t分?jǐn)?shù)\t學(xué)號(hào)");
while(rs.next()){
System.out.print(rs.getString(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getInt(3)+"\t");
System.out.println(rs.getInt(4)+"\t");
}
}