I have some doubt when accessing to my SQL DB. The thing is I have a connect Button with this code:
public void actionPerformed(ActionEvent arg0) {
Object opc = arg0.getSource();
if (opc.equals(v.conectar))
{
Connection conexion = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conexion = DriverManager.getConnection("jdbc:mysql://localhost/colegio", "root", "12345");
Statement stm = conexion.createStatement();
JOptionPane.showMessageDialog(null, "CONEXION ESTABLECIDA CON EXITO");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
In that button, as you see, I connect perfectly with my DB. The problem appears when I need to acced to that Statement object from other JInternalFrame:
public class boton_alta_cliente implements ActionListener {
ventanaAlta v;
boton_alta_cliente(ventanaAlta v) {
this.v=v;
}
public void actionPerformed(ActionEvent arg0, Statement STM) {
Object opc = arg0.getSource();
if (opc.equals(v.alta))
{
ResultSet RS = STM.executeQuery("query");
}
}
}
How can I use that connection I made in my first button, in the JInternalFrame that I use for sign up my clients?
You could create a separate class in your project that handles JDBC connections. So for example, you could have a class called "JDBC" which creates a connection in a "connect()" method. You could then call that connection from your other classes like so:
Connection connect = JDBC.connect();
Like any reference to an object that you want to share between objects, it has to be defined not as a local variable but as a (preferably private) field. You create a getter method for it, and the other frame can use the getter method to access the connection. The same goes for the prepared statement.
Related
Im trying to gain access to my database using a project in order to input information like username and password so that if the input is correct, then i can access details about that certain account, but before all that, there's an error that says "java.lang.ClassNotFoundException:org.apache.derby.jdbc.EmbeddedDriver"
and im not sure how to fix it, i checked other solutions saying to check my URL, which i have done and fixed but it still is an error
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
try{
//REGISTER THE DRIVERS
Class.forName(JDBC_Driver1);
Class.forName(JDBC_Driver2);
//ESTABLISH CONNECTION TO DB
System.out.println("Connecting to a selected Database....");
con=DriverManager.getConnection(URL,USER,PASS);
System.out.println("CONNECTED SUCCESSFULLY");
}
catch (Exception e){
System.err.println(e);
I am not sure which IDE you are using. I will explain this in terms of the Netbeans IDE.
Firstly, you will need to make sure you have a Glassfish type server. They can be found in the "services" tab.
Secondly, you need to make sure your derby database is connected. In netbeans if it is not connected, it will have a broken looking icon next to it. If this is the case, right click and hit connect.
One of the benefits to a derby database is that it has a built in set of drivers, so it is unnecessary to provide a driver class.
If you are completely starting out fresh and have not changed your username or password, the following code has all of the default information to connect to the sample database that is created when you download glassfish server.
public class DataAccessDerby {
private static final String URL = "jdbc:derby://localhost:1527/sample";
private static final String USER = "app";
private static final String PASS = "app";
Connection con;
Statement stmt;
public void openConnection() throws ClassNotFoundException, SQLException {
con = DriverManager.getConnection(URL, USER, PASS);
}
public void closeConnection() throws SQLException {
if (con != null) {
con.close();
}
}
public static void main(String[] args) {
DataAccessDerby derby = new DataAccessDerby();
try {
System.out.println("Connecting to a selected Database....");
derby.openConnection();
System.out.println("CONNECTED SUCCESSFULLY");
derby.closeConnection();
} catch (ClassNotFoundException | SQLException e) {
System.err.println(e);
}
}
}
I hope this helps.
I am learning about MySQL database and I cannot quite understand one concept. Lets say there are two methods in the same class as the one shown below. Now, do i have to use Connection connect = dbConnection.getDBConnection(); in each method or is there a different way to declare one connection and use it across multiple methods?:
private void setUpdateButton(ActionEvent event) {
try{
Connection connect = dbConnection.getDBConnection();
Statement stmt = connect.createStatement();
if(txtID.getText().trim().isEmpty()||txtFirstName.getText().trim().isEmpty() || txtSecondName.getText().trim().isEmpty() ||
txtGender.getText().trim().isEmpty() || txtAge.getText().trim().isEmpty() || txtHomeAddress.getText().trim().isEmpty() || txtPhoneNumber.getText().trim().isEmpty()) {
showAlert("Invalid Input!", "All fields need to be populated before updating.");
}else {
String sqlQuery ="update student_information set Age ='"+Integer.parseInt(txtAge.getText())+"',Name ='"+txtFirstName.getText()+"',Surename='"+txtSecondName.getText()
+"',Gender='"+txtGender.getText()+"',Address='"+txtHomeAddress.getText()+"',PhoneNumber='"+txtPhoneNumber.getText()+"'where ID="+Integer.parseInt(txtID.getText());
stmt.executeLargeUpdate(sqlQuery);
setTxtArea();
showConfAlert("Update Completed!", "Record has been updated!");
Creating connections is a costly operation, so I think you should open the connection at the application startup, and close it on exit.
If your program is not multi thread you would be fine with a simple global object, otherwise other strategies should be used.
You can create a singleton for your app with a method returning the connection.
public class App {
private static App self;
private Connection connection;
private App(){
}
public synchronized App getInstance(){
if(self == null){
self = new App();
}
return self;
}
public synchronized Connection getConnection()throws SQLException {
if(connection==null || !isValid(connection)){
// Create a new connection
}
return connection;
}
private boolean isValid(Connection conn) {
// Check if the connection is valid otherwise return false
return false;
}
public static synchronized void close(){
try{
self.connection.close();
} catch (SQLException e){
// Swallow exception
} finally {
self = null;
}
}
}
You can get the connection anywhere like this:
Connection conn = App.getInstance().getConnection();
You should make sure to close the connection on exit, maybe with a shutdown hook.
You could also, create a wrapper around your connection that forwards all connection methods to the original connection , with the exception of close that marks the connection available , this way you create something like 1 connection pool.
If the connection is available you return it otherwise you either wait or throw or do what is most appropriate for your application.
I want to populate a JComboBox with a database column (SQLite).
My database connection is setup through a class called DatabaseConnection setup in anther package.
Here is how it looks like
import java.sql.*;
import javax.swing.JOptionPane;
public class DatabaseConnection {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:database.db");
JOptionPane.showMessageDialog(null, "Connection Established");
conn.setAutoCommit(false);
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
In my JFrame class I am creating following method, which according to a youtube tutorial should work
public void PopulateJCB()
{
String queryString = "SELECT DISTINCT [Account Name] FROM main ORDER BY [Account Name]";
try
{
Connection statJCBaccountname = DatabaseConnection.ConnectDB();
Statement stmt = statJCBaccountname.createStatement();
ResultSet rsJCBaccountname = stmt.executeQuery(queryString);
while (rsJCBaccountname.next())
{
comboAccountName.addItem(rsJCBaccountname.getString(1));
}
catch (SQLException e)
{
e.printStackTrace();
}
}
But it displays following errors at "comboAccountName.addItem(rsJCBaccountname.getString(1));"
Multiple markers at this line
- Type safety: The method addItem(Object) belongs to the raw type JComboBox. References to generic type JComboBox<E> should be
parameterized
- comboAccountName cannot be resolved
Please help!
I'm not really sure what you're expecting...
statJCBaccountname isn't even in the code example you've provided, but the compiler is saying that the variable is undefined
There is no such method as createStatement in the DatabaseConnection class
You need to resolve these issues before the program will compile. I'd suggest staying away from YouTube tutorials unless you know the author.
Take a look at JDBC Database Access for more details...
Currently, I load the below custom driver (TestDriver.java), get a connection, create a Statement, execute a query, gets the results and close the connection. I open and close a connection for each query. Is this common practice or is there an standard way to share the open connections?
public static void main(String[] args) {
Class.forName("com.sql.TestDriver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:test://8888/connectme", props);
Statement stmt = conn.createStatement;
ResultSet rs = stmt.executeQuery("select * from table");
//loop through rs and pull out needed data
conn.close();
}
public class TestDriver implements java.sql.Driver{
private final TestSchema schema;
private Properties props = null;
static {
try {
DriverManager.registerDriver(new TestDriver());
} catch (SQLException e) {
e.printStackTrace();
}
protected TestDriver() throws SQLException {
schema = TestSchemaFactory.getInstance().getDbSchemaFromFile(SCHEMA_FILE);
//loads in and parses a file containing tables, columns used for business logic
}
public Connection connect(String url, Properties info)
throws SQLException {
TestSqlConnection conn=null;
//connect logic here
return conn; //will return an instance of TestSqlConnection
}
#Override
public boolean jdbcCompliant() {
return false;
}
}
Yes, it's more common to use a database connection pool. This will allow connections to be reused without the overhead or closing/re-opening. Here's a link to DBCP which is one implementation of a database connection pool: http://commons.apache.org/dbcp/
Ideally you should write a separate factory class (can be static)
say ConnectionFactory which returns a connection object.
Also I see that you are not using try/catch/finally block while creating
connection.I strongly suggest to close the connection in finally
clause otherwise you program may suffer from connection leak if any
exception is raised and causes abrupt behavior.
Ideally you should close the connection after your operation is complete in finally
clause.In web based application if you are using connections pool
then closing connection will return the connection back to pool and
will be available for use.
Is it possible to store a database connection as a separate class, then call the database objects from a main code? ie;
public class main{
public static void main{
try{
Class.forName("com.jdbc.driver");
Database to = new Database(1,"SERVER1","DATABASE");
Database from = new Database(2,"SERVER2","DATABASE");
String QueryStr = String.format("SELECT * FROM TABLE WHERE Id = %i", to.id)
to.results = sql.executeQuery(QueryStr);
while (to.results.next()) {
String QueryStr = String.format("INSERT INTO Table (A,B) VALUES (%s,%s)",to.results.getString(1),to.results.getString(2));
from.sql.executeQuery("QueryStr");
}
to.connection.close()
from.connection.close()
} catch (Exception ex) {
ex.printStackTrace();
{ finally {
if (to.connection != null)
try {
to.connection.close();
} catch (SQLException x) {
}
if (from.connection != null)
try {
from.connection.close();
} catch (SQLException x) {
}
}
}
public static class Database {
public int id;
public String server;
public String database;
public Connection connection;
public ResultSet results;
public Statement sql;
public Database(int _id, String _server, String _database) {
id = _id;
server = _server;
database = _database;
String connectStr = String.format("jdbc:driver://SERVER=%s;port=6322;DATABASE=%s",server,database);
connection = DriverManager.getConnection(connectStr);
sql = connection.createStatement;
}
}
}
I keep getting a "Connection object is closed" error when I call to.results = sql.executeQuery("SELECT * FROM TABLE"); like the connection closes as soon as the Database is done initializing.
The reason I ask is I have multiple databases that are all about the same that I am dumping into a master database. I thought it would be nice to setup a loop to go through each from database and insert into each to database using the same class. Is this not possible? Database will also contain more methods than shown as well. I am pretty new to java, so hopefully this makes sense...
Also, my code is probably riddled with syntax errors as is, so try not to focus on that.
Connection object is closed doesn't mean that the connection is closed, but that the object relative to the connection is closed (it could be a Statement or a ResultSet).
It's difficult to see from your example, since it has been trimmed/re-arranged, but it looks like you may be trying to use a ResultSet after having re-used its corresponding Statement. See the documentation:
By default, only one ResultSet object per Statement object can be open
at the same time. Therefore, if the reading of one ResultSet object is
interleaved with the reading of another, each must have been generated
by different Statement objects. All execution methods in the Statement
interface implicitly close a statment's current ResultSet object if an
open one exists.
In your example, it may be because autoCommit is set to true by default. You can override this on the java.sql.Connection class. Better yet is to use a transaction framework if you're updating multiple tables.