1.JDBC操作mysql数据库-增删改查
//查询数据
@Test
public void testQuery(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.注册驱动
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.获取执行SQL的statement
stmt = conn.createStatement();
//4.执行SQL
String sql = "select * from user";
stmt.execute(sql);
rs = stmt.getResultSet();
//5.处理结果
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数据库-增删改查
public void exeCuteQuery()throws Exception{
Connection conn=null;
//1.加载驱动
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.创建sql语句
String sql="select * from student order by stuid,score desc";
//执行命令获取结果集
ResultSet rs=st.executeQuery(sql);
System.out.println("姓名\t科目\t分数\t学号");
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");
}
}
网友评论