JAVABEAN连接各数据库

时间:2021-11-28 08:42:58

1.  连接ACCESS( AccessBean.java)

package access;

import java.sql.*;

public class AccessBean

{

String driver="sun.jdbc.odbc.JdbcOdbcDriver";

Connection connect=null;

ResultSet rs=null;

public AccessBean(){

try{

Class.forName(driver);

}catch(Exception e){

e.printStackTrace();

}

}

public ResultSet query(String sql){

try{

connect=DriverManager.getConnection("jdbc:odbc:student","","");

Statement stmt=connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

rs=stmt.executeQuery(sql);

}catch(Exception e){

e.printStackTrace();

}

return rs;

}

public void update(String sql){

try{

connect=DriverManager.getConnection("jdbc:odbc:vote","","");

Statement stmt=connect.createStatement();

stmt.executeUpdate(sql);

}catch(Exception e){

e.printStackTrace();

}

}

};

2.  连接SQLSERVER(SqlServerBean.java)

package sql;

import java.sql.*;

public class SqlServerBean

{

String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";

Connection connect=null;

ResultSet rs=null;

public SqlServerBean(){

try{

Class.forName(driver);

}catch(Exception e){

e.printStackTrace();

}

}

public ResultSet query(String sql){

try{

connect=DriverManager.getConnection("jdbc:microsoft:sqlserver://ts06:1433;Database         Name=mydata","sa","sa");

Statement stmt=connect.createStatement();

rs=stmt.executeQuery(sql);

}catch(Exception e){

e.printStackTrace();

}

return rs;

}

public void update(String sql){

try{

connect=DriverManager.getConnection("jdbc:microsoft:sqlserver://ts06:1433;DatabaseName=mydata","sa","sa");

Statement stmt=connect.createStatement();

stmt.executeUpdate(sql);

}catch(Exception e){

e.printStackTrace();

}

}

};

3.  连接ORACLE

package  oracle;

import java.sql.*;

public class OracleBean

{

String serverName=”localhost”;

String driver="oracle.jdbc.driver.OracleDriver";

String url=”jdbc:oracle:thin:@”+serverName+”:1521:OEMREP”;

Connection connect=null;

ResultSet rs=null;

public OracleBean(){

try{

Class.forName(driver);

}catch(Exception e){

e.printStackTrace();

}

}

public ResultSet query(String sql){

try{

connect=DriverManager.getConnection(url,”system”,”manager”);

Statement stmt=connect.createStatement();

rs=stmt.executeQuery(sql);

}catch(Exception e){

e.printStackTrace();

}

return rs;

}

public void update(String sql){

try{

connect=DriverManager.getConnection(url,”system”,”manager”);

Statement stmt=connect.createStatement();

stmt.executeUpdate(sql);

}catch(Exception e){

e.printStackTrace();

}

}

};

Statement stmt=connect.createStatement()括号内可以加参数:

ResultSet.TYPE_SCROLL_INSENSITIVE表示结果集可以滚动,但对数据库变化不敏感

ResultSet.CONCUR_READ_ONLY表示结果集不能用于更新数据库

ResultSet.TYPE_FORWARD_ONLY结果集不滚动

ResultSet.TYPE_SCROLL_SENSITIVE结果集可以滚动,而且对数据库变化不敏感

ResultSet.CONCUR_UPDATE可用于更新数据库