Click to See Complete Forum and Search --> : JavaBean to Retrieve Information


Stinger100
03-07-2006, 05:40 PM
Hi,

I am trying to write a JavaBean to retrieve information from a database (MySQL). I have tried the below but this does not seem to work. To be honest I'am a bit confused what files I require to create to do this. I would be grateful if someone could clarify what I need to do to retrieve information from my database.
I also need to return the records in a vector. If someone is able to help me with the coding I will grateful.


// import required packages
import java.sql.*;
import java.util.*;
import java.util.Vector.*;

public class db_connector
{
private String url = "";
private String driver = "";
private String un = "";
private String pw = "";
private Vector results = new Vector();

// Creates a new instance of db_connector
public db_connector()
{
url = "jdbc:mysql://localhost:3306/content";
driver = "com.mysql.jdbc.Driver";
un = "root";
pw = "mysql";
}

public void setSettings(String url, String driver, String un, String pw)
{
this.url = url;
this.driver = driver;
this.un = un;
this.pw = pw;
}

public Vector getLastRecords()
{
return results;
}

public Vector getRecords(String sql)
{
Vector dataset = new Vector();
try
{
// Set up the JDBC connection

// Pull in the driver
Class.forName(driver);


String query = sql;

// Get a connection to the database
Connection connection = DriverManager.getConnection(url, un, pw);

// Create a database statement to use to run the query
Statement statement = connection.createStatement();

// Execute the query
boolean success = statement.execute(query);

if(success)
{
// Pull out the results into a Resultset
ResultSet rs = statement.getResultSet();
ResultSetMetaData rsMetaData = rs.getMetaData();
while (rs.next())
{
Vector row = new Vector();
// Populate the Vector in accordance to how many columns the resultset contains
for (int i=0; i<=rsMetaData.getColumnCount(); i++)
{
row.addElement(rs.getObject(i));
}
results.addElement(row);
// Close the resultset
rs.close();
}
// Clean up by closing the statement and the connection
statement.close();
connection.close();
}
}
// catch any errors
catch(Exception e)
{
e.printStackTrace();
}
return results;
}

}

regards
Stinger

Khalid Ali
03-07-2006, 06:52 PM
Read the sticky at the top of this forum regarding troublshooting basic problems, I have written some basic info on how to deal with MySQL.
Once you go thru that then see if that leads to some changes in ur code, if not then post your errors that u get when trying to use ur code. A detailed error must be posted for a better response...