Mysql 数据库和Oracal数据库的连接

时间:2021-10-12 13:06:15

Mysql数据库的连接:(这个例子我只是测试Connection是否为null,检测是否连接成功)

package JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class search {
    private static final String driver="com.mysql.jdbc.Driver";  private static final String url="jdbc:mysql://localhost:3306/"
+"json?useSSL=false&useUnicode=true&characterEncoding=utf-8";
private static final String user="root"; private static final String password="1234"; private static Connection conn=null; static { try { Class.forName(driver); //注册驱动 } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() { try { conn=DriverManager.getConnection(url, user, password); //建立连接 return conn; } catch (SQLException e) { e.printStackTrace(); return null; } } public static void main(String [] args) { Connection conn=search.getConnection(); if(conn!=null) { System.out.println("连接数据库成功"); }else { System.out.println("连接数据库失败"); } } }

 

Oracle数据连接:

package hello.ant; 

import java.sql.*; 

public class jdbc{ 
//设定一些参数
String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"; 
String user="root"; 
String password="1234"; 
Connection conn=null; 
Statement s; 
ResultSet r=null; 

public jdbc(){ 

try{ 
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();  //注册驱动
conn = DriverManager.getConnection(url,user,password);           //建立连接
s=c.createStatement();                                           //创建Statement
   }catch(Exception e){ 
    e.printStackTrace(); 
   } 
} 

public boolean executeUpdate(String sql){    //根据传进来的sql语句更新数据库的数据
try { 
s.executeUpdate(sql); 
return true; 
   }catch (SQLException e) 
   { 
    e.printStackTrace(); 
    return false; 
    } 
} 

public ResultSet executeQuery(String sql){    //根据传进来的sql语句查询数据库的数据,并返回结果集r
try { 
r=s.executeQuery(sql); 
}catch(SQLException e) { 
     e.printStackTrace(); 
    } 
return r; 
} 


public void close() {                        //将结果集和statement关闭
try { 
    r.close(); 
    s.close(); 
}catch(Exception e) { 
     e.printStackTrace(); 
    } 
} 

public static void main(String[] args){ 

ResultSet r; 

   jdbc j = new jdbc();   //实例化Model类
   r=j.executeQuery("select * from test"); //调用查询的方法,并将sql语句传过去
try{ 
    while (r.next()){ //遍历结果集
    System.out.println(r.getString("id")); 
    System.out.println(r.getString("name"));    //打印查询到的数据
   } 
}catch(Exception e){ 
    e.printStackTrace(); 
} 
} 
}