记得在项目中加入jar包
JDBC 连接Oracle
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class main {
Connection con=null;
Statement sta = null;
ResultSet res = null;
public Connection openOrcl(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
String url = "jdbc:oracle:thin:127.0.0.1:1521:orcl";
String UserName = "system";
String UserPass = "123456";
con = DriverManager.getConnection(url, UserName, UserPass);
} catch (Exception e) {}
return con;
}
public int update(String sql)
{
int re=0;
try {
sta=con.createStatement();
re = sta.executeUpdate(sql);
} catch (Exception e) {}
return re;
}
public ResultSet select(String sql){
try {
sta=con.createStatement();
res = sta.executeQuery(sql);
} catch (Exception e) {}
return res;
}
public void closeOrcl() {
try{
res.close();
sta.close();
con.close();
}catch(Exception e){}
}
}
JDBC连接MySQL
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DataServer {
Connection con=null;
Statement sta = null;
ResultSet res = null;
DataServer() throws SQLException {
this.openMysql();
}
public Connection openMysql() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
System.out.println("error");
}
String url="jdbc:mysql://localhost:3306/cs";
String name="root";
String pass="123";
con = DriverManager.getConnection(url,name, pass);
return con;
}
public int update(String sql)
{
int re=0;
try {
sta=con.createStatement();
re = sta.executeUpdate(sql);
} catch (Exception e) {}
return re;
}
public ResultSet select(String sql) throws SQLException {
try {
sta=con.createStatement();
res = sta.executeQuery(sql);
} catch (Exception e) {}
return res;
}
public void closeMysql() {
try{
res.close();
sta.close();
con.close();
}catch(Exception e){}
}
}
|