using a Java DB Connection in another form - java

I have created a simple Java connection script in Java to connect to a database shown below.
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class dbconn {
public static void main(String[] args) throws ClassNotFoundException
{
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:C:/Program Files (x86)/Spiceworks/db/spiceworks_prod.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}
Now I have tested this connection via some SQL queries inside the dbconn script and it works.
However my question is, how would Icall this instance of the database into another form in the same project to preform the same SQL queries which are:
ResultSet resultSet = null;
resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next())
{
System.out.println("EMPLOYEE Email: " + resultSet.getString("email"));
}

You can retain and reuse the Connection, saving it probably in some static field. If you access it from multiple threads, SQLite must work in the Serialized mode. You must have the code somewhere to re-establish the connection if it has been lost for some reason.
If the use of Connection is not heavy, you can also have some method that opens it and close when no longer needed, better inside the finally block.

Related

Cannot access H2 server from remote machine

I have a new H2 test DB all setup and have no issue getting to it locally.
I used this site to help https://www.tutorialspoint.com/h2_database/h2_database_jdbc_connection.htm
I took the code and put it up on an Amazon web server and can confirm it is indeed running and can, again, locally add data to it and access it VIA code and the H2 console. The H2 console can even be reached from my remote PC.
Now on my PC I am trying to get to the server VIA JDBC but cannot. Server is even set up for the TCP server.
in the properties file
spring.datasource.url=jdbc.h2.mem.test
In the application.java file, in a try-catch, and it reports the server did start.
Server.createTcp.Server().start();
The DB has a table called testable in there with server columns and test rows. And Again locally and even in the H2 console, I can get to the data no problem.
I tried several ways to list the URL in Java code to get to the server VIA JDBC.
here is the fake URL that I can get to a website hosted there just fine as well as the H2 console.
https://www.mywebsitehostedonamazon.com/h2
I have added this to my code to the connection for the URL.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class H2jdbcCreateDemo {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:tcp://https://www.mywebsitehostedonamazon.com:8082/test";
// Database credentials
static final String USER = "sa";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 1: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 3: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "SELECT * FROM testable LIMIT 1";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
// STEP 4: Clean-up environment
stmt.close();
conn.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try{
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
} // nothing we can do
try {
if(conn!=null) conn.close();
} catch(SQLException se){
se.printStackTrace();
} //end finally try
} //end try
System.out.println("Goodbye!");
}
}
When I run this I receive a Zero length string error for line conn = DriverManager.getConnection(DB_URL,USER,PASS);
If I change up the URL then I get a connection time out. jdbc:h2:tcp://www.mywebsitehostedonamazon.com:8082/test
If I change up the URL then I get a connection time out. jdbc:h2:tcp://www.mywebsitehostedonamazon.com:8082/mem:test
If I change up the URL then I get an error that the Table "testable" not found. jdbc:h2:mem://www.mywebsitehostedonamazon.com:8082/mem:test
Can anyone help out with this?

connecting to database(postgres) with java in intellij

I want to write a code to get my queries from input and run it and show me the result.I have to connect to database in my code.
I connected to postgres by intellij database extension and my queries run in the console.
but i want to do that in my code(i mean get the queries from user and run it).
is it possible to use this database connection and run queries on it?
i got connected successfully by this code too :
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/db","postgres", "pass");
and i wrote some queries.
all query types(such as update , delete , insert , ...) run and the result is visible in the pgadmin but i want to have the result in my java code
Here is an example to run a query with JDBC. you can download the JDBC here https://jdbc.postgresql.org/download.html and added to your classpath
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PostgreSqlExample {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/example", "postgres", "postgres")) {
System.out.println("Java JDBC PostgreSQL Example");
System.out.println("Connected to PostgreSQL database!");
Statement statement = connection.createStatement();
System.out.println("Reading car records...");
System.out.printf("%-30.30s %-30.30s%n", "Model", "Price");
ResultSet resultSet = statement.executeQuery("SELECT * FROM public.cars");
while (resultSet.next()) {
System.out.printf("%-30.30s %-30.30s%n", resultSet.getString("model"), resultSet.getString("price"));
}
} /*catch (ClassNotFoundException e) {
System.out.println("PostgreSQL JDBC driver not found.");
e.printStackTrace();
}*/ catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}

Accessing Oracle DB express from within Java

I have a basic Java application (with a GUI) that uses a linked list to add/remove/modify Customer objects and I want to store them in a database (Oracle DB express to be exact)?
As I understand it, I have to create a table with some tool, and the use that tool to auto-generate a Java class that would allow me to communicate with the DB. How far off am I with this?
Just to make your question clear, What tool have you used to generate your java code?
I recommend you to avoid using code generation tool in case you want to learn in and out of Java.Here is an example of how you can connect your SWING application with Oracle DB,MySQL,Derby and many more other databases.
Connection con;
Statement smt;
ResultSet rs;
String user="databaseuser";
String pass="password";
String path="jdbc:oracle:thin:#localhost:1521:Sampledb"; //put db url here
try{
con=DriverManager.getConnection(path, user, pass);
smt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String SQL="SELECT *FROM Registered_users_tb "; //Your Query here
rs=smt.executeQuery(SQL);
rs.moveToInsertRow();
//First param is db column name,second param is variable name
rs.updateString("USERNAME", username);
rs.updateString("FNAME", fname);
rs.updateString("MNAME", mname);
rs.updateString("LNAME", lname);
rs.updateString("GENDER", gender);
rs.updateString("DEPARTMENT", dept);
rs.insertRow();
rs.close();
smt.close();
}
catch(SQLException err){
JOptionPane.showMessageDialog(Classname.this,err.getMessage());
}
For creating a complete new database, oracle provide a gui tool called DBCA. I found a couple of links to use this tool: Link 1 and Link 2
This tutorial teaches how to access an Oracle database. For accessing such an database you need additional drivers found here. Here an short example how to access such a database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
class DatabaseAccess
{
public static void main(String [] args)
{
Connection connection = null;
try
{
Class.forName("oracle.jdbc.OracleDriver");
String dbPath = "jdbc:oracle:thin:#localhost:1521:myDatabase";
String username = "user";
String password = "password";
connection = DriverManager.getConnection(dbPath, username, password);
if(connection != null)
{
System.out.println("Connected with database");
Statement statement = connection.createStatement();
ResultSet results = statementt.executeQuery("SELECT * FROM myTable");
while(result.next())
{
System.out.println(result.getString("myString"));
}
}
catch(ClassNotFoundException | SQLException exc)
{
exc.printStackTrace();
}
finally
{
try
{
connection.close();
}
catch(SqlException exc)
{
exc.printStackTrace();
}
}
}
}
For an more advanced example visit the given link.

ucanaccess SQL Exception: invalid cursor state: identified cursor is not open

I am a little bit confused,
I am trying to insert multiple rows to MS Access database from a java program using ucanaccess Java library.
I don't understand why the above (check title) SQL Exception is thrown when calling the 2nd insertRow() method?
The Exception is NOT thrown either by calling con.setAutoCommit(false); & con.commit(); methods or by re-executing the SQL query using the command rs = st.executeQuery(sql);. I also do not understand why the problem is solved by doing one of the above. What changes?
Thanks in advance.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class db1 {
private Connection con;
protected Statement st;
protected ResultSet rs;
public db1() {
connect();
}
public void connect() {
try {
String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
Class.forName(driver);
String db = "jdbc:odbc:Database1";
con = DriverManager.getConnection
("jdbc:ucanaccess://C:\\Users\\Κώστας\\Desktop\\Database1.accdb");
st = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE,
ResultSet.HOLD_CURSORS_OVER_COMMIT)
// con.setAutoCommit(false);
String sql = "select * from TableA";
rs = st.executeQuery(sql);
rs.insertRow();
// rs = st.executeQuery(sql);
rs.insertRow(); // HERE the SQL Exception is thrown.
// con.commit();
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
new db1();
}
}
UCanAccess has some known issues with updatable ResultSets because it uses triggers on the HSQLDB backing tables to push the changes to the Access database file. A side effect of those triggers is that they can leave the HSQLDB ResultSet in an invalid state.
The problem you are experiencing may not manifest itself with con.setAutoCommit(false); because the triggers probably don't flush the changes to the Access database until the JDBC transaction is committed.

Creating JDBC Connections Outside The DAO

So I just finished learning JDBC this weekend and have successfully transferred my code from the main method into an MVC app. The purpose of this application is to hold a roster of players and display a users credentials if requested. The program works great and when I request a url like...
http://localhost:8084/gmustudent/players?id=1
I get the correct output for that player! The problem is I am performing the database connection within my PlayersDAO class and I assume that this is not the "best" way to do this. So I have two questions.
Is there a way to perform the database connection within the web.xml
file or some other file so that when the server is initially started it will
immediately perform the connection to the database and be ready to
query when asked?
And is this actually a better alternative to having the connection in the DAO or would this have unforeseen negative drawbacks. AKA would a constant connection to my database be exactly what I do not want?
Any comments or links would be greatly appreciated. And I'll share the code I currently have for my DAO class so that you can see what I have so far. Thank you all!
package com.jdbc.test;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
public class PlayersDAO
{
public static Players viewPlayer(int id) throws SQLException
{
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
Players playerObject = null;
try
{
String url = "jdbc:mysql://localhost:3306/gmustudent";
String username = "root";
String password = "root";
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException error)
{
System.out.println("Error: " + error.getMessage());
}
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM players WHERE id = " + id);
if(resultSet.next())
playerObject = new Players(resultSet.getLong("id"), resultSet.getString("name"), resultSet.getString("position"), resultSet.getString("height"), resultSet.getString("year"), resultSet.getString("hometown"), resultSet.getString("highschool"), resultSet.getString("headshot"));
}
finally
{
if (connection != null) try{connection.close();} catch(SQLException ignore) {}
if (statement != null) try{statement.close();} catch(SQLException ignore) {}
if (resultSet != null) try{resultSet.close();} catch(SQLException ignore) {}
}
return playerObject;
}
}
You can create database connection in web.xml file by using resource. I hope this tutorial will help you.
http://viralpatel.net/blogs/database-connection-pooling-tomcat-eclipse-db/
You can use JDBC Connection Pooling.It can provide significant benefits in terms of application performance, concurrency and scalability.
IMHO, its always a good approach to hide the instantiation details of any resources. You can use factory method to do this. The advantage of this approach is that you can always change the way to manage the resources - e.g. You can have one instance of JDBCConnection per DAO or you can have connection pool. Any time you can provide your development specific db connection, test specific db connection or production db connection. All these details you can hide doing such approach.

Categories

Resources