Du bruger denne klasse:
import java.sql.*;
/**
*
* @author srr
* @version
*/
public class dbHandler extends Object
{
private Connection con=null;
/** Creates new DataBase */
public dbHandler()
{
}
public boolean open(String dbDriverName, String dbClassName, String user, String pass)
{
// System.out.println(\"************************************************************************\");
try
{
if(con==null)
{
Class.forName(dbDriverName).newInstance();
con = DriverManager.getConnection(dbClassName, user, pass);
// System.out.println(\"con = \"+con);
}
}
catch (SQLException e)
{
e.printStackTrace(System.out);
return false;
}
catch (ClassNotFoundException e)
{
e.printStackTrace(System.out);
return false;
}
catch (InstantiationException e)
{
e.printStackTrace(System.out);
return false;
}
catch (IllegalAccessException e)
{
e.printStackTrace(System.out);
return false;
}
return true;
}
public void close()
{
if(con!=null)
{
try
{
con.close();
con=null;
}
catch (SQLException e)
{
e.printStackTrace(System.out);
}
}
}
public int doUpdate(String sql)
{
if(con!=null)
{
try
{
long time=System.currentTimeMillis();
Statement stat=con.createStatement();
// System.out.println(\"SQL Update = \"+(System.currentTimeMillis()-time)+\" ms \"+sql);
return stat.executeUpdate(sql);
}
catch (SQLException e)
{
e.printStackTrace(System.out);
}
}
return 0;
}
public ResultSet doQuery(String sql)
{
if(con!=null)
{
try
{
long time=System.currentTimeMillis();
Statement stat=con.createStatement();
// System.out.println(\"SQL Update = \"+(System.currentTimeMillis()-time)+\" ms \"+sql);
return stat.executeQuery(sql);
}
catch (SQLException e)
{
e.printStackTrace(System.out);
}
}
return null;
}
}
Og kalder den med denne her:
import dk.ecsoft.database.mysql.*;
/**
*
* @author srr
* @version
*/
public class Database extends dbHandler
{
/** Creates new Database */
public Database()
{
}
public boolean open()
{
return super.open(\"org.gjt.mm.mysql.Driver\",\"jdbc:
mysql://SERVERNAVN/DATABASENAVN\",\"BRUGERNAVN\",\"PASSWORD\");
}
}
Så kalder du doQuery() med en sql streng og får et resultset tilbage.