java实现三种数据库连接完整的demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanzhix/article/details/48682861

都是源码直接复制过来的,可直接粘用微笑

public class A {

public static Connection conn; 
public static ResultSet rs = null ;    
public static Statement st = null ;

public static void main(String[] args) {

getConnection("127.0.0.1", "3306", "ly", "root", "root", "c");
}


public static void getConnection(String ip,String port,String dbname,String user,String pwd,String type){    
String url = "";
try {

       //初始化驱动包     
       try {
        //判断需要连接的数据库类型
        if(type.equals("a")){
       
        //sqlserver 连接
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            url = "jdbc:sqlserver://" + ip + ":" + port + ";databaseName=" + dbname;
        }else if(type.equals("b")){
       
        //oracle 连接
        Class.forName("oracle.jdbc.driver.OracleDriver");
               url = "jdbc:oracle:thin:@" + ip + ":" + port + ":" + dbname;
        }else{
        //mysql 连接
        Class.forName("com.mysql.jdbc.Driver");
        url = "jdbc:mysql://" + ip + ":" + port + "/" + dbname ;
        }
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动类加载失败!");
}
       
       //连接数据库
       try {
conn=DriverManager.getConnection(url, user, pwd);
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败!");
}
       
       //查询
       List<Map> list = new ArrayList<Map>();
       st = conn.createStatement();
       String sql = " select * from user ";
       rs = st.executeQuery(sql);
       while (rs.next()) {     
        Map<String,String> map = new HashMap<String,String>();
    map.put("id", rs.getString("id"));
    map.put("name",  rs.getString("name"));
    map.put("rolekey",  rs.getString("rolekey"));
    list.add(map);
       }
       System.out.println("2222222==="+list);
       
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭(必须有)
try {
if(rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}

}
    }   

}
展开阅读全文

没有更多推荐了,返回首页