如何调用这个类中的连接方法?
如何调用这个类中的连接方法?请写出代码
package javaapplication2;
/**
*
* @author Administrator
*/
import java.sql.*;
public class Conn
{
String sDBDriver;
Connection connect;
Statement stmt;
ResultSet rs;
String URL;
String user;
String password;
public Conn()
{
sDBDriver = "oracle.jdbc.driver.OracleDriver";
connect = null;
stmt = null;
rs = null;
URL = "jdbc:oracle:thin:@17.1.2.235:1521:ODSDEV";
user = "odsdev";
password = "odsdev";
try
{
Class.forName(sDBDriver);
}
catch(
ClassNotFoundException classnotfoundexception)
{
System.err.println(classnotfoundexception.getMessage());
}
}
public ResultSet executeQuery(String s)
{
try
{
connect = DriverManager.getConnection(URL, user, password);
stmt = connect.createStatement();
rs = stmt.executeQuery(s);
}
catch(
SQLException sqlexception)
{
System.err.println(sqlexception.getMessage());
}
return rs;
}
public void endconn()
{
try
{
stmt.close();
connect.close();
}
catch(SQLException sqlexception)
{
System.err.println(sqlexception.getMessage());
}
}
public String callprocedure(String s)
{
try
{
connect = DriverManager.getConnection(URL, user, password);
String s1 = s;
CallableStatement callablestatement = connect.prepareCall(s1);
callablestatement.executeUpdate();
connect.close();
}
catch(SQLException sqlexception)
{
System.err.println(sqlexception.getMessage());
}
return "ok boy";
}
}
------解决方案--------------------Java code
Conn co = new Conn();//已经连接上了
ResultSet rs = co.executeQuery(...);//...填sql
//处理rs,略
co.endconn();
------解决方案--------------------
看错了,下面是正确的
Conn co = new Conn();//未连接上
ResultSet rs = co.executeQuery(...);//...填sql,执行前自动会连接
//处理rs,略
co.endconn();
------解决方案--------------------
连接的方法
sDBDriver = "oracle.jdbc.driver.OracleDriver";
connect = null;
stmt = null;
rs = null;
URL = "jdbc:oracle:thin:@17.1.2.235:1521:ODSDEV";
user = "odsdev";
password = "odsdev";
try
{
Class.forName(sDBDriver);
}
catch(ClassNotFoundException classnotfoundexception)
{
System.err.println(classnotfoundexception.getMessage());
}
被放入了构造器中,当实例化这个类时,上面的代码就会执行;
如果你要单独调用上面的代码,你这个类不能那么做;
如果你需要连接数据库操作,可以在该类中下面再创建个方法,