-
JDBC between classes
I have one class which has two methods. One which opens a connection and one that closes it.
Code:
import java.util.*;
import java.sql.*;
public class DatabaseUtils
{
String driver = "oracle.jdbc.driver.OracleDriver";
public static Connection con(String driver, String url, String username, String password)
throws ClassNotFoundException, SQLException
{
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
// Similar methods to close Statement and ResultSet
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Now in another class, i am trying to do a query. This is what i have done
Code:
import java.util.*;
import java.sql.*;
public class PersonDAO{
public static void main(String args[])
{
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String userName = "scott";
String passWord = "tiger";
PersonInfo person = new PersonInfo();
DatabaseUtils.con("<driver>", "<url>", "<userName>", "<passWord>");
try
{
String sql = "INSERT INTO Person(name, idNo, " +
"userName, passWord) VALUES (?,?,?,?) ";
// Create a Preparedstatement
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, person.getName());
ps.setString(2, person.getIdNo());
ps.setString(3, person.getUsername());
ps.setString(4, person.getPassword());
ps.executeUpdate();
}
catch(Exception e){
System.out.println(e);
}
}
}// end class PersonDAO
I am being returned with the error cannot find symbal variable con, relating to the con.preparedstatement. Where abouts am i going wrong?
-
You haven't declared any variable with the "con" name in your code. You should modify your way to obtain the connection object to:
Code:
Connection con = DatabaseUtils.con(driver, url, userName, passWord);
Anyway, why did you cann the method with something like "<driver>", etc?