Reputation: 3
I'm having a bit of trouble with this bit of syntax:
Connection con = null;
Statement st = null;
ResultSet rset = null;
/**
* Creates new form formUsers
*/
public formUsers() {
initComponents();
con = SQLInteract.SQLInteract();
tableUpdate();
}
I am attempting to call the connection to a MySQL database I have already made, which is contained in the constructor method for the class. Am I merely screwing up the syntax in some way, or can I not do that at all? Or is it really as simple as just using:
SQLInteract Connect = new SQLInteract();
As requested; here is the SQLInteract syntax:
Connection con = null;
Statement st = null;
ResultSet rset = null;
public SQLInteract() {
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/chemsimdb","root","");
}catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Upvotes: 0
Views: 156
Reputation: 6650
You said you have already made a connection to the database. I assume you did it this way:
SQLInteract sqlInteract = new SQLInteract();
Then, what you need to do is the following:
public formUsers() {
initComponents();
con = sqlInteract.con;
tableUpdate();
}
But of course, the SQLInteract
instance you created before must be available where ever you want the connection.
Additionally, I strongly recommend you go by the Java naming convention that requires classes' (and constructors') names to start with an uppercase letter, while variables', methods' (other than constructors) and attributes' names start with a lowercase letter.
Upvotes: -1
Reputation: 1254
You must either create a new instance using the constructor:
SQLInteract connect = new SQLInteract();
Or you said you have already made a connection which I assume is represented by an instance of SQLInteract and so you must pass this reference of the existing instance to the new class. PS: It is good practise to name your classes with capital letters so formUsers should be FormUsers
public FormUsers(SQLInteract existingSqlConncetion) {
initComponents();
//con will hold a reference to the SQLInteract instance that has previously been constructed
con = existingSqlConnection;
tableUpdate();
}
Upvotes: 2
Reputation: 616
It sounds to me (though I may be wrong) that you shouldn't be calling a constructor if the MySQL connection is already established in that class. You should be using an already instantiated object of that class that holds a reference to the MySQL connection and simply asking for that connection.
If you mean by ' I have already made' you mean that the code that connects to the DB is in that constructor and you simply want to call it then yes you must create a new object:
SQLInteract connect = new SQLInteract();
The small difference between that and what you wrote is the lowercase C in connect, remember here you are naming a member object, not a class (i assume that was just a typo by you, but jsut making sure)
Upvotes: 0