I was working on a java project and it was working just fine. I was able to make connections. I closed all the connections properly in finally block. Now I am not able to make connections or even open psql in my terminal. How can I make it work as before. Much much appreciated
import java.sql.Connection;
import com.mchange.v2.c3p0.*;
public class MyConnection {
public static Connection getConnection(){
ComboPooledDataSource cpds1 = new ComboPooledDataSource();
String dbDriver = "org.postgresql.Driver";
String dbName = "jdbc:postgresql://localhost/postgres";
cpds1.setJdbcUrl(dbName);
String userName = "user_1";
cpds1.setUser(userName);
String password = "mypass";
cpds1.setPassword(password);
cpds1.setMaxStatements( 180 );
try
{
cpds1.setDriverClass(dbDriver);
return cpds1.getConnection();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
This is where I'm calling it
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter writer = response.getWriter();
JSONObject jo = new JSONObject();
JSONObject jObj;
Statement stmt = null;
Connection con = null;
PreparedStatement ps;
ResultSet rs = null;
try
{
jObj = UtilityClass.getJSON(request);
String uname = ((String) jObj.get("uname"));
String pass = ((String) jObj.get("pass"));
String sql = "SELECT * FROM users WHERE username = ?";
try
{
con = MyConnection.getConnection();
System.out.println("Got Connection");
stmt = con.createStatement();
ps = con.prepareStatement(sql);
ps.setString(1, uname);
rs = ps.executeQuery();
if(rs.next())
{
if(BCrypt.checkpw(pass,rs.getString("password")))
{
HttpSession session = request.getSession();
session.setAttribute("uname", uname);
if(session.isNew())
{
System.out.println("new");
}
if(uname.equals("admin"))
{
session.setAttribute("role", "admin");
jo.put("status", "admin");
}
else
{
session.setAttribute("role", "user");
jo.put("status", "authenticate");
}
}
}
writer.print(jo);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Not Connected");
}
finally
{
if(rs != null)
{
rs.close();
}
if(stmt != null)
{
stmt.close();
}
if(con != null)
{
con.close();
}
}
}
catch(Exception e)
{
System.out.print("JSON Exception");
}
}
Usually, DB Admins are using pooling technologies on Databases. For PostgreSQL one of the more popularly is a PGBOUNCER. We used PGBOUNCER in our large project, the result is excellent. I recommend it to you. To get more information about the pooling system you can read this link. For About Pooling
Related
I'm trying to connect to my DB using JDBC. I wanted to make a method for connection and another method for selecting data. I am getting a red line in Eclipse on the 'Connection con = connectDB();' part. ( See also attached) Cany anyone give me advice?
public class DBJdbc {
//Statement stmt = null;
// connecting to DB
public void connectDB() {
//Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
// a method for selecting DB
public static void select() {
//connectDB();
String sql = "SELECT * from SAC_SUR";
try(Connection con = connectDB(); // I'm getting a red line here)
PreparedStatement pstmt = con.prepareStatement(sql)){
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("Id = " + id + "name = " + name);
} //while
} catch(SQLException e) {
System.out.println(e.getMessage());
}
}
red line here!!!
connectDB() method is of void type and not returning anything but when you are calling the method, you are assigning it to variable con. So you need to change the return type of connectDb to the Connection type.
public Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
You are trying to call non-static method into the static area, which is not allowed in Java. So I made this method static and returning the database connection.
Please update the below method into your code. It will resolve your problem.
public static Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "", "");
} catch(SQLException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
I have a servlet deployed on a Jetty 9 server that connects to a MySQL 5.6.17 server using the Connector/J JDBC driver from http://dev.mysql.com/downloads/connector/j/5.0.html.
This particular servlet fires a SQL statement inside a for loop that iterates around 10 times. I have to include the
DriverManager.getConnection(DB_URL, USER, PASSWORD);
line within this loop because the connection closes automatically after the SQL statement has been executed in every iteration of the loop.
Is there a way to keep the connection open, so that getConnection() need be executed only once before the loop starts and then i can manually close it in the finally block.
I have found many posts on this particular issue, but all refer to the connection pooling concept as the solution. But i am just interested in avoiding the connection being closed automatically after each query execution. Shouldn't this be a simple parameter? I am not facing any particular performance problem right now, but it just seems to be a waste of processor and network cycles.
Servlet Code :
public class CheckPhoneNumberRegistrationServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
System.err.println("started CheckPhoneNumberRegistrationServlet");
// define database connection details
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = DatabaseParameters.SlappDbURL;
final String USER = DatabaseParameters.DbServer_Username;
final String PASSWORD = DatabaseParameters.DbServer_Password;
PreparedStatement prpd_stmt = null;
Connection conn = null;
ResultSet rs = null;
int resultValue;
// open a connection
/*try {
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}*/
JsonParser jsparser;
JsonElement jselement;
JsonArray jsrequestarray;
JsonArray jsresponsearray = new JsonArray();
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) {
e.printStackTrace();
}
try {
jsparser = new JsonParser();
jselement = (JsonElement) jsparser.parse(jb.toString());
jsrequestarray = jselement.getAsJsonArray();
for (int i = 0; i < jsrequestarray.size(); i++) {
// System.err.println("i : " + i +
// jsrequestarray.get(i).toString());
try {
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
prpd_stmt = conn
.prepareStatement("select slappdb.isPhoneNumberRegistered(?)");
prpd_stmt.setString(1, jsrequestarray.get(i).toString()
.replace("\"", ""));
rs = prpd_stmt.executeQuery();
if (rs.first()) {
//System.err.println("result sert from sql server : " + rs.getString(1));
//slappdb.isPhoneNumberRegistered() actually returns Boolean
//But converting the result value to int here as there is no appropriate into to Boolean conversion function available.
resultValue = Integer.parseInt(rs.getString(1));
if(resultValue == 1)
jsresponsearray.add(jsparser.parse("Y"));
else if(resultValue == 0)
jsresponsearray.add(jsparser.parse("N"));
else throw new SQLException("The value returned from the MySQL Server for slappdb.isPhoneNumberRegistered(" + jsrequestarray.get(i).toString().replace("\"", "") + ") was unexpected : " + rs.getString(1) + ".\n");
// System.err.println("y");
}
else throw new SQLException("Unexpected empty result set returned from the MySQL Server for slappdb.isPhoneNumberRegistered(" + jsrequestarray.get(i).toString().replace("\"", "") + ").\n");
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (prpd_stmt != null)
prpd_stmt.close();
} catch (SQLException e1) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException e1) {
}
}
}
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
// resp.setContentLength(1024);
resp.getWriter().write(jsresponsearray.toString());
System.err.println(jsresponsearray.toString());
} catch (Exception e) {
// crash and burn
System.err.println(e);
}
The problem is that you're closing the connection inside the for loop. Just move both statements: connection opening and connection close, outside the loop.
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
for (int i = 0; i < jsrequestarray.size(); i++) {
try {
//current code...
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (prpd_stmt != null)
prpd_stmt.close();
} catch (SQLException e1) {
}
}
}
try {
if (conn != null)
conn.close();
} catch (SQLException e1) {
}
When i run my website it on glassfish server everything works fine but after some time its stop responding and I need to restart glassfish.. I think its cause I not closing the connection. Can someone tell me if this is the problem? if yes how to close it? Here is one of my function.
public Album get_album (String title)
{
try{
//creates a connection to the server
Connection cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
PreparedStatement pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
ResultSet rs = pst.executeQuery();
if(rs.next()) {
Album a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
return a;
}
}
catch (Exception e) {
String msg = e.getMessage();
}
return null;
}
Assumming the unique error in your application is for not closing the resources after using them, your code should change to:
public Album get_album (String title) {
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Album a = null;
try{
//creates a connection to the server
cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
rs = pst.executeQuery();
if (rs.next()) {
a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
//don't return inside try/catch
//return a;
}
} catch (Exception e) {
String msg = e.getMessage();
//handle your exceptions
//e.g. show them in a logger at least
e.printStacktrace(); //this is not the best way
//this will do it if you have configured a logger for your app
//logger.error("Error when retrieving album.", e);
} finally {
closeResultSet(rs);
closeStatement(pst);
closeConnection(cn);
}
return a;
}
public void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeStatement(Statement st) {
if (st!= null) {
try {
st.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeResultSet(ResultSet rs) {
if (rs!= null) {
try {
rs.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
i am using xampp mysql, this code is for JDBC program. actually there are two class one is dbconnect.java and another is login.java. I want to access the connection object (i.e. conn) in another class(i.e. login.java). But i don't have proper idea, i have included the code here please suggest me what is the problem and what are the solutions?
This is the code of dbconnect.java
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 is the code from another class named login.java
if(source==login){
if(username!=null && password!=null) {
Connection conn= null;
Statement stmt = null;
dbconnect db = new dbconnect();
db.conect();
String query = "SELECT * from userlogin";
try{
stmt=(Statement) conn.createStatement(); // here is the problem
ResultSet rs = stmt.executeQuery(query); // here is the problem
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);
}
}
What is the real problem and how to solve it?
The easiest way would be to make the connect method non void and return the connection:
public Connection 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");
}
return con;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
You should return your CONNECTION object from you connection class and assign it to your login class... Now your connection object is null...
I wrote a servlet whose purpose is to login into the application only if the query executes...now what is the condition to be used for invalid username and id...I'm unable to write the condition..pls help me out...the servlet is...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl ","scott","tiger");
System.out.println("cnnection est");
int Id = Integer.parseInt(request.getParameter("id"));
String Name=request.getParameter("firstname");
boolean b=true;
//Connection con =JdbcConnectionUtil.getConnection();
PreparedStatement pst = con.prepareStatement("select * from login where id=? and firstname=?");
pst.setInt(1, Id);
pst.setString(2, Name);
ResultSet rs = pst.executeQuery();
if(rs!=null && rs.next())
{
//while(rs.next()){
PrintWriter pw = response.getWriter();
System.out.println("here");
pw.println("hello");
pw.println(rs.getInt(1));
pw.println(rs.getString(2));
pw.println(rs.getString(3));
}
//}
else
{
RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");
}
//
}
catch(Exception ex){
ex.printStackTrace();
}
}
Using rd.forward will solve the problem I think.
How to forward requests from Servlet to JSP
First you check for the correct parameters and then you do the logic. Also do not forget to close statements and connections to avoid memory leaks.
Here is refactored code:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//get parameters from request
try {
String idParam = request.getParameter("id");
String name = request.getParameter("firstname");
//check if request contains such parameters
if (idParam == null || name == null) {
throw new IllegalArgumentException(
"Id and Name parameters must not be null.");
}
//try casting idParam to int
Integer id = null;
try {
id = Integer.parseInt(idParam);
} catch (NumberFormatException nfe) {
throw nfe;
}
PreparedStatement pst = null;
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl ", "scott", "tiger");
pst = con.prepareStatement(
"select * from login where id=? and firstname=?");
pst.setInt(1, id);
pst.setString(2, name);
//check if result returned any data
ResultSet rs = pst.executeQuery();
if (!rs.next()) {
throw new Exception(
"No such user for id: " + id + " and name: " + name);
}
PrintWriter pw = response.getWriter();
pw.println("hello");
pw.println(rs.getInt(1));
pw.println(rs.getString(2));
pw.println(rs.getString(3));
} catch (Exception ex) {
throw ex;
} finally {
try {
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException sqle) {
throw sqle;
}
}
} catch (Exception ex) {
ex.printStackTrace();
RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");
rd.forward(request, response);
}
}
Something like that would be appropriate I think.