Re: how to access connection object in another class?
On 02/19/2013 04:18 AM, xodepp shrestha wrote:
Here is the source code.
This is the code to connect the database.
package stundentrecord;
import java.sql.Connection;
import java.sql.DriverManager;
public class dbconnect {
public void conect(){
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "studentRecord";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
if(con==null){
System.out.println("Connection cannot be established");
}
// con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
AND HERE I WANT TO USE connection OBJECT BUT IT IS SHOWING ERROR.WHAT TO DO ??
if(source==login){
if(username!=null && password!=null){
Connection conn= null;
Statement stmt = null;
dbconnect db = new dbconnect();
String query = "SELECT * from userlogin";
try{
stmt=(Statement) conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
String user = rs.getString("username");
String pass=rs.getString("password");
System.out.println("Welcome "+user);
}
}catch(SQLException ex){
ex.getMessage();
}
StundentRecord SR = new StundentRecord();
}else{
JOptionPane.showMessageDialog(null,"Username or password field is empty","error !!",JOptionPane.ERROR_MESSAGE);
}
}
Where is that second set of code, what class and package? Is it in the
same package, likely not. Do you have an import statement that refers to
the "dbconnect" class? If not, fully qualify it when you reference it.
Other notes:
1. I realize your 1st language is not English; nevertheless
professionalism (and respect for any language that you use) demands that
I point out a few typos - StudentRecord -> StudentRecord, conect() ->
connect().
2. CamelCase your class names, e.g. DbConnect.
3. Your 'url' + 'db' concatenation, *everything* joined is potentially
the JDBC URL, including username and password. Since you're hard-coding
the DB name anyway, just add it to the 'url' variable.
4. Your username and password validation: do you think that's sufficient
to see if either is null? Is an empty username OK?
5. If your code got multiple rows back from the 'userlogin' table it
wouldn't think that was a problem. Also, don't just copy code withoput
understanding it - just because you get a ResultSet doesn't mean you
have to also run a while() loop on it; if you expect one row and must
have one row, a while() loop would be clumsy and obscure that logic.
6. Don't - even in learning code - do that absolute noop with an
exception. Please.
AHS