连接Oracle:
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestOracle {
private static String driver="oracle.jdbc.OracleDriver";
private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
private static String user="scott";
private static String password="root2306";
public static void main(String[] args) {
ResultSet rs=null;
Statement statement=null;
Connection connection=null;
try{
//注册数据库的驱动
Class.forName(driver);
//获取数据库连接
connection=DriverManager.getConnection(url,user,password);
statement=connection.createStatement();
rs=statement.executeQuery("select * from users");
while(rs.next()){
System.out.println(rs.getString("username"));
System.out.println(rs.getString("age"));
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
//释放数据库资源
try{
if(rs!=null)
{
rs.close();
rs=null;
}if(connection!=null){
connection.close();connection=null;
}if(statement!=null){
statement.close();statement=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
连接MySQL:
package test;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Connection;
public class TestMysql {
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://106.14.182.157:3306/test";
private static String user="root";
private static String password="root";
public static void main(String[] args) {
ResultSet rs=null;
Statement statement=null;
Connection connection=null;
try{
//注册数据库的驱动
Class.forName(driver);
//获取数据库连接
connection=DriverManager.getConnection(url,user,password);
statement=connection.createStatement();
rs=statement.executeQuery("select * from users");
while(rs.next()){
System.out.println(rs.getString("username"));
System.out.println(rs.getString("age"));
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
//释放数据库资源
try{
if(rs!=null)
{
rs.close();
rs=null;
}if(connection!=null){
connection.close();connection=null;
}if(statement!=null){
statement.close();statement=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
对比一下,是不是一样一样滴!!!!