JAVA; How to make SQL getConnection(); as main variable / prime? - java

I would like to ask how to make Connection con = getConnection(); becaome a primer or main variable so that it would not connect to SQL database every function made. Because as you can see on my codes, every function/class has Connection con = getConnection(); so it connects to the database every function. It makes my program process slowly. Please help thank you.
package march30;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
public class sqltesting {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
get();
}
public static void lookup() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename where id=6");
ResultSet result = statement.executeQuery();
if (result.next()) {
System.out.println("First Name: " + result.getString("first"));
System.out.println("Last Name: " + result.getString("last"));
}
else {
System.out.println("No Data Found");
}
} catch (Exception e) {}
}
public static ArrayList<String> get() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while (result.next()) {
System.out.print(result.getString("first"));
System.out.print(" ");
System.out.println(result.getString("last"));
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
System.out.println(Arrays.asList(array));
return array;
} catch (Exception e) {System.out.println((e));}
return null;
}
public static void update() throws Exception{
final int idnum = 2;
final String var1 = "New";
final String var2 = "Name";
try {
Connection con = getConnection();
PreparedStatement updated = con.prepareStatement("update tablename set first=?, last=? where id=?");
updated.setString(1, var1);
updated.setString(2, var2);
updated.setInt(3, idnum);
updated.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Update Completed");
}
}
public static void delete() throws Exception{
final int idnum = 7;
try {
Connection con = getConnection();
PreparedStatement deleted = con.prepareStatement("Delete from tablename where id=?");
deleted.setInt(1, idnum);
deleted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Delete Completed");
}
}
public static void post() throws Exception{
final String var1 = "Albert";
final String var2 = "Reyes";
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO tablename (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Insert Completed");
}
}
public static void createTable() throws Exception {
try {
Connection con = getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))");
create.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Function Completed");
}
}
public static Connection getConnection() throws Exception{
try {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://xxxxxxxx.amazonaws.com:3306/pointofsale";
String username = "xxxxx";
String password = "xxxxxx";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}

To solve your problem you need to store a Connection object in your sqltesting class as a class member. You then need to reference the Connection object instead of getConnection(). It's also worth mentioning that Connection is a AutoClosable object so you need to close this resource when you're done with it, I.E; on application disposal. You also might want to consider using a connection pooling API like Hikari or C3P0 so you can open and close connections when you need them instead of having 1 open for a long time.
class SQLTesting {
private final Connection connection;
public SQLTesting(Connection connection) {
this.connection = connection;
}
public SQLTesting() {
this(getConnection());
}
// other methods
private Connection getConnection() {
// your method to create connection, rename to createConnection maybe.
}
}

Related

Why jdbc statement doesn't make changes in mysql table

statement.executeUpdate("DELETE FROM persons WHERE id=1");
statement.executeUpdate("UPDATE persons SET first_name = 'first' WHERE
id=3");
statement.executeUpdate("DELETE FROM persons WHERE first_name = 'Dmitrij';");
These statements don't make changes in table in DBeaver. Why not? Two first statements are executed in Idea, and make Delete and Set, but only in jdbc, not it Mysql. The third even not executed in Idea. Can anybody clear it to me?
public class MeetingService {
private static Connection connection;
private static final String URL = "jdbc:mysql://localhost:3306/homeworks?user=root&password=123456";
private List<Person> users;
MeetingService() {
this.users = new ArrayList<>();
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection getConnection() {
if (Objects.isNull(connection)) {
try {
connection = DriverManager.getConnection(URL);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
and then i have a method:
void deleteFromUsers() throws SQLException {
try(Statement statement = getConnection().createStatement()) {
statement.executeUpdate("DELETE FROM persons WHERE id=1");
statement.executeUpdate("UPDATE persons SET first_name = 'first' WHERE id=3");
statement.executeUpdate("DELETE FROM persons WHERE first_name = 'Dmitrij';");
}
}
Remove semicolon(;) in
'Dmitrij';
try it like
statement.executeUpdate("DELETE FROM persons WHERE first_name = 'Dmitrij'");
I didn't find any wrong in the below source code and have tested and running fine.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class MeetingService {
private static Connection connection;
private static final String URL = "jdbc:mysql://localhost:3306/homeworks?user=root&password=password";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection getConnection() {
if (connection == null) {
try {
connection = DriverManager.getConnection(URL);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
void deleteFromUsers() throws SQLException {
try(Statement statement = getConnection().createStatement()) {
statement.executeUpdate("DELETE FROM persons WHERE id = 1");
statement.executeUpdate("UPDATE persons SET first_name = 'first' WHERE id=3");
statement.executeUpdate("DELETE FROM persons WHERE first_name = 'Dmitrij'");
}
}
public static void main(String[] args) throws SQLException {
MeetingService service = new MeetingService();
service.deleteFromUsers();
}
}
both delete and single update is running fine and there is nothing to do with semicolon.

JDBC: can't send parameters from client to Derby DB by using servlet and Apache Tomcat

I'm try to send the parameters from servlet to db and I get errors in my connection.
Steps of my works:
In eclipse I create a Dynamic Web Project with Tomcat server
Create a model (without any technology as a Spring , Hibernate, JSP, JSF and so on. ) for to use with DML methodology (clearing java code).
I tested the created module (by using some main test class) and it works so good (connections , inserting, deleting..).
After that , I can a simple HTML doc for client side.
process for running a web module step by step:
Before start Web project I start to run Derby DB - works OK.
Starting a Web project with Apache Tomcat.
insert data to the HTML and submitted it. - works OK
In the Servlet class the data gated to the doGet(...) method. - works OK.
From the Servlet (doGet(...) method) when I try to send the parameter to the DB I get errors in my conector class.
How can I set right that?
Thanks.
Codes:
Servlet Class:
#WebServlet({ "/StudentServlet", "/Student" })
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDbDao sf = new StudentDbDao();
private Student student = new Student();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
String studentId = request.getParameter("sudentId");
Long id = Long.parseLong(studentId);
String studentFullName = request.getParameter("studentFullName");
String studentGendre = request.getParameter("studentGendre");
String studentGrade = request.getParameter("studentGrade");
try {
student.setId(id);
student.setFullName(studentFullName);
student.setGender(studentGendre);
student.setGrade(studentGrade);
sf.createStudent(student);
writer.println("The student #" + id + " inserted.");
} catch (StudentSystemException e) {
e.printStackTrace();
}
}
}
class StudentDbDao that response for DML functionality:
package dao.Db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import bean.Student;
import bean.StudentSystemException;
import dao.StudentDao;
import dao.connector.ConnectionPool;
public class StudentDbDao implements StudentDao {
private Connection conn;
public StudentDbDao() {
}
#Override
public void createStudent(Student student) throws StudentSystemException {
conn = ConnectionPool.getInstance().getConnection();
String sql = "INSERT INTO Students(ID, FULLNAME, GENDER, GRADE) VALUES(?, ?, ?, ?)";
PreparedStatement pstmt;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, student.getId());
pstmt.setString(2, student.getFullName());
pstmt.setString(3, student.getGender());
pstmt.setString(4, student.getGrade());
pstmt.executeUpdate();
System.out.println(student.getFullName() + " created successfully");
} catch (SQLException e) {
throw new StudentSystemException("Failed!", e);
} finally {
ConnectionPool.getInstance().returnConnection(conn);
}
}
#Override
public void removeStudent(Student student) throws StudentSystemException {
conn = ConnectionPool.getInstance().getConnection();
String sql = "DELETE FROM Students WHERE ID = " + student.getId();
PreparedStatement pstmt;
try {
pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
System.out.println(student.getId() + " removed successfully.");
} catch (SQLException e) {
throw new StudentSystemException("Failed!", e);
} finally {
ConnectionPool.getInstance().returnConnection(conn);
}
}
#Override
public Student getStudentById(long id) throws StudentSystemException {
conn = ConnectionPool.getInstance().getConnection();
String sql = "SELECT * FROM Students WHERE ID = " + id;
Student student = new Student();
PreparedStatement pstmt;
ResultSet rs;
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if (rs.next()) {
student.setId(rs.getLong(1));
student.setFullName(rs.getString(2));
student.setGender(rs.getString(3));
student.setGrade(rs.getString(4));
}
// else {
// System.out.print("Student with PID #" + id + " not exists. ");
// }
return student;
} catch (SQLException e) {
throw new StudentSystemException("Failed!", e);
} finally {
ConnectionPool.getInstance().returnConnection(conn);
}
}
public long getMaxRows() throws StudentSystemException {
conn = ConnectionPool.getInstance().getConnection();
String sql = "SELECT COUNT(*) FROM Students";
PreparedStatement pstmt;
int count = 0;
try {
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
rs.next();
count = rs.getInt(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
ConnectionPool.getInstance().returnConnection(conn);
}
return count;
}
}
class ConnectionPool where code is falls when Servlet try to set the parameters:
public class ConnectionPool {
// static final int MAX_CONS = 1;
private Connection myconn = null;
// private Set<Connection> connections = new HashSet<Connection>();
private static ConnectionPool instance = new ConnectionPool();
String url = "jdbc:derby://localhost:1527/StudentDB";
private ConnectionPool() {
try {
myconn = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static ConnectionPool getInstance() {
return instance;
}
public Connection getConnection() {
// Connection conn = myconn;
return this.myconn;
}
public void returnConnection(Connection conn) {
this.myconn = conn;
// myconn.add(conn);
}
public void closeAllConnections() throws StudentSystemException {
Connection connection = myconn;
try {
connection.close();
} catch (SQLException e) {
throw new StudentSystemException("Failed to close connection: ", e);
}
}
attached before submit and after print-screens:
before:
after:

How to insert data into database from the main file?

I've got 2 file in my java project : MysqlConnect and Main .
I want to run query from Main class.It's possible?
This is MysqlConnect file:
public class MysqlConnect {
public Connection conn = null;
public String url = "jdbc:mysql://localhost:3306/";
public String dbName = "jdbctutorial";
public String driver = "com.mysql.jdbc.Driver";
public String userName = "birthday";
public String password = "123456";
public Statement stmt;
public String query = "";
public int rs;
public void crearedatabase() {
try {
Class.forName(driver).newInstance();
conn = DriverManager
.getConnection(url + dbName, userName, password);
// System.out.println("Connected to the database");
Statement stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Baza de date nu a fost creata");
}
}
public void executeSql() {
try {
rs = stmt.executeUpdate(query);
} catch (Exception e) {
System.out.println("Mysql Error");
}
}
}
And this is the Main file:
public class Main {
public static void main(String[] args) throws SQLException
{
MysqlConnect sqlconnect = new MysqlConnect();
sqlconnect.crearedatabase();
sqlconnect.query="INSERT INTO `jdbctutorial`.`persons` (`id`, `nume`, `prenume`, `data`) VALUES (NULL, 'xxxx', 'xxxx', '1990-12-12');";
sqlconnect.executeSql();
}
}
The error(Exception) is on the MysqConnection at the try/catch
rs = stmt.executeUpdate(query);
You assign statement object to a local variable named stmt instead of the object field with the same name.
Replace this
Statement stmt = conn.createStatement();
With this:
this.stmt = conn.createStatement();
this is not necessary here, but it's a good practice to have it there.

simple data comparison with MySQL, nullpointerexception

I'm currently being thrown into the depths by my school and they are expecting me to program a simple login form using sql. They have given us brief examples on how they use JDBC and what it all is, but haven't really explained step by step how to use it on our own. Therefore i have snatched a bit of code from an example but i'm unable to get it working. I keep receiving an nullpointerexception and i can't figure out why :(
Here's the connection class:
package Database;
import java.sql.*;
public class MySQLConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://localhost/corendon";
public static final String DBUSER = "root";
public static final String DBPASS = "simplepass";
private ResultSet result = null;
private int affectedRows = -1;
Connection conn = null;
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
}
}
public void closeConnection() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (Exception e) {
}
conn = null;
}
public ResultSet performSelect(PreparedStatement prdstmt) throws SQLException {
result = prdstmt.executeQuery();
return result;
}
public int performUpdate(PreparedStatement prdstmt) throws SQLException {
affectedRows = prdstmt.executeUpdate();
return affectedRows;
}
public Connection getConnection() {
return conn;
}
}
And here is the method i'm getting the exception in (in a different class):
MySQLConnection conn = new MySQLConnection();
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
prdstmt = conn.getConnection().prepareStatement(query);
prdstmt.setInt(1, id);
prdstmt.setString(2, pass);
rs = conn.performSelect(prdstmt);
while (rs.next()){
String tempPass = rs.getString("password");
int tempId = rs.getInt("id");
}
if(conn != null){
conn.closeConnection();
}
}
I'm getting the nullpointerexception on line:
prdstmt = conn.getConnection().prepareStatement(query);
Why does it throw an exception there, but not when i start the connection and also how do i solve this? Thanks in advance.
When you call startConnection(), you are throwing an Exception
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
//An exception occurs here, but you don't do anything about it
}
}
Therefore, when you call getConnection(), the conn variable is still null, which is throwing the NullPointerException.
Either make startConnection() throw an exception so that you're forced to deal with it (this is usually how most JDBC drivers work anyway), or check to see if the conn variable is null before you start using it.
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
if (conn.getConnection() == null) {
throw new SQLException("Connection is null!");
}
Or (what I think would personally be better)
public void startConnection() throws Exception {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
}
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
try {
conn.startConnection();
} catch (Exception e) {
throw new SQLException(e);
}
Also as a tip, you should probably avoid declaring your classes as the same name of other classes you are using. This is all happening in your own MySQLConnection class, but that could be confusing with the actual com.mysql.jdbc.MySQLConnection class.

If I use a singleton class for a database connection, can one user close the connection for everybody?

I wrote a singleton class for obtaining a database connection.
Now my question is this: assume that there are 100 users accessing the application. If one user closes the connection, for the other 99 users will the connection be closed or not?
This is my sample program which uses a singleton class for getting a database connection:
public class GetConnection {
private GetConnection() { }
public Connection getConnection() {
Context ctx = new InitialContext();
DataSource ds = ctx.lookup("jndifordbconc");
Connection con = ds.getConnection();
return con;
}
public static GetConnection getInstancetoGetConnection () {
// which gives GetConnection class instance to call getConnection() on this .
}
}
Please guide me.
As long as you don't return the same Connection instance on getConnection() call, then there's nothing to worry about. Every caller will then get its own instance. As far now you're creating a brand new connection on every getConnection() call and thus not returning some static or instance variable. So it's safe.
However, this approach is clumsy. It doesn't need to be a singleton. A helper/utility class is also perfectly fine. Or if you want a bit more abstraction, a connection manager returned by an abstract factory. I'd only change it to obtain the datasource just once during class initialization instead of everytime in getConnection(). It's the same instance everytime anyway. Keep it cheap. Here's a basic kickoff example:
public class Database {
private static DataSource dataSource;
static {
try {
dataSource = new InitialContext().lookup("jndifordbconc");
}
catch (NamingException e) {
throw new ExceptionInInitializerError("'jndifordbconc' not found in JNDI", e);
}
}
public static Connection getConnection() {
return dataSource.getConnection();
}
}
which is to be used as follows according the normal JDBC idiom.
public List<Entity> list() throws SQLException {
List<Entity> entities = new ArrayList<Entity>();
try (
Connection connection = Database.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id, foo, bar FROM entity");
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
Entity entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setFoo(resultSet.getString("foo"));
entity.setBar(resultSet.getString("bar"));
entities.add(entity);
}
}
return entities;
}
See also:
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
Below code is a working and tested Singleton Pattern for Java.
public class Database {
private static Database dbIsntance;
private static Connection con ;
private static Statement stmt;
private Database() {
// private constructor //
}
public static Database getInstance(){
if(dbIsntance==null){
dbIsntance= new Database();
}
return dbIsntance;
}
public Connection getConnection(){
if(con==null){
try {
String host = "jdbc:derby://localhost:1527/yourdatabasename";
String username = "yourusername";
String password = "yourpassword";
con = DriverManager.getConnection( host, username, password );
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
}
return con;
}
While getting Connection in any Class simply use below line
Connection con = Database.getInstance().getConnection();
Hope it may help :)
package es.sm2.conexion;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConexionTest {
private static Connection conn = null;
static Connection getConnection() throws Exception {
if (conn == null) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "userparatest";
String password = "userparatest";
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
}
return conn;
}
}
To close Connection
public static void closeConnection(Connection conn) {
try {
conn.close();
} catch (SQLException e) {
}
}
To call to the connection:
package conexion.uno;
import java.sql.*;
import es.sm2.conexion.ConexionTest;
public class LLamadorConexion {
public void llamada() {
Connection conn = null;
PreparedStatement statement = null;
ResultSet resultado = null;
String query = "SELECT * FROM empleados";
try {
conn = ConexionTest.getConnection();
statement = conn.prepareStatement(query);
resultado = statement.executeQuery();
while (resultado.next()) {
System.out.println(resultado.getString(1) + "\t" + resultado.getString(2) + "\t" + resultado.getString(3) + "\t" );
}
}
catch (Exception e) {
System.err.println("El porque del cascar: " + e.getMessage());
}
finally {
ConexionTest.closeConnection(conn);
}
}
}
Great post, farhangdon! I, however, found it a little troublesome because once you close the connection, you have no other way to start a new one. A little trick will solve it though:
Replace if(con==null) with if(con==null || con.isClosed())
import java.sql.Connection;
import java.sql.DriverManager;
public class sql11 {
static Connection getConnection() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/ics", "root", "077");
return c;
}
}

Categories