Connection To A Database In Its Own Class
Jan 15, 2015
I was wondering if I could take the following code and somehow put the connection to database in it's own class without the "public static void main(String[] args)" method. That way I could call it anytime i want to open a connection to the database.
Java Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample {
public static void main(String[] args) throws ClassNotFoundException
[Code] ....
View Replies
ADVERTISEMENT
Jan 15, 2015
I have a shop and I use visual studio.net to create an Inventory application to manage my shop. So I am familiar with vb.net codes.
Now, I'm trying to built another Inventory application for my shop using java, 'coz now I'm using Linux Ubuntu for my OS desktop and there's no visual studio.net in linux.
So in vb.net, there's a module that I use for database connection that I can call from any form that I needed.
I searched google for the equivalent module for java and there is none. But, there's an example that use a new java class.
Here's the code in MySQLConnect.java :
Java Code:
public class MySQLConnect {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/dbInventory";
static final String USER = "root";
static final String PASS = "root";
public static Connection ConnectDb() {
[Code] ....
View Replies
View Related
Oct 27, 2014
I'm using oracle 10g Database and Java 'jdk1.7.0_45' version.I have to a create program to insert data into a table.
View Replies
View Related
Sep 16, 2014
I'm using JSF framework. I can let Netbeans to create the persistence unit and hardcodes connection parameters into the persistence.xml file or i can use resource tag in context.xml file or using another file like property file or class for holding connection parameters like username and password; what is the most secure way or expert way to use connection properties in my app or there is no difference?
View Replies
View Related
Mar 15, 2015
I am trying to make a simple login using netbeans, derby database included in netbeans and tomcat server. I made everything nice and separated: I have a model package with a class called DbConnector that has the following method:
public Connection connect() {
try {
return DriverManager.getConnection(url, user, pass);
} catch (SQLException ex) {
return null;
}
}
Then i have another class, an userDAODB that has a password check method:
public boolean checkPassword(String user, String password) {
try (Connection con = new DbConnector().connect(); Statement stmt = con.createStatement()) {
//checks the password in the database
In the main method of this class i tested everything, it works very nice, logs me in, other methods work too, no problem what so ever.But then i go to my servlet:
public class LoginTest extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String username = request.getParameter("username");
String pass = request.getParameter("pass");
UserDAODB userDAO = new UserDAODB();
boolean authe = userDAO.checkPassword(username, pass);
[code]....
So when i start the webpage and i try to click on the login button I get a NullPointerException com.model. UserDAODB. check Password (User DAODB. java:14) - so line 2 here
I have been googling a bit, i placed the derby.jar and the derbyclient.jar in the lib directory of tomcat, i tried to modify the context.xml of my application, but then it wouldn't even start anymore.
View Replies
View Related
Oct 7, 2014
i have a problem in connecting my jsp program in MSsql 2005 i want to create a connection in my jsp program to MSsql database but theres an error of my work here is my code
Code:
PHP Code:
<%@ page import="java.util.*" %>
<%@ page import="javax.sql.*;" %>
<%@ page import="java.sql.*;" %>
<%@ page import="java.util.Enumeration;" %>
<html>
<head><title>Sample MS connection</title></head>
[Code]...
View Replies
View Related
May 21, 2014
I am trying to make connection with oracle database but when i run java file it's raise an error
"classnotfoundexception oracle.jdbc.driver.oracledriver"
DriverManager.getConnection(
"jdbc:oracle:thin:@erp:1521:ORCL", "apps",
"apps");
View Replies
View Related
Jul 10, 2015
I have small Java code, which execute every day and checks for data in database using Cronj Schedular and everything works fine, but recently I have observed that, it is failing due to
java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@160.110.xx.xxx:1521/test
At the same time, when I run my test code to check Database connectivity that works fine without above exception. I'm unable to figure it out. Although, there was just slight code change, but that was nowhere related to Database or Database connection.
dbconf.java
public class dbconf {
private Connection connect;
private String connstr;
public Connection getConnection() throws SQLException {
connstr = "jdbc:oracle:thin:@160.110.xx.xxx:1521/test";
[Code] ....
Application Log file
Wed Jul 01 09:25:17 IST 2015:------- Initializing -------------------
Wed Jul 01 09:25:17 IST 2015:------- Scheduling Jobs ----------------
Wed Jul 01 09:25:17 IST 2015:------- Job Started Running ----------------
Thu Jul 02 06:00:00 IST 2015 : Job Executed..!! Bschedularv2.2
java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@160.xxx.67.xxx:1521/test
Sat Jul 04 06:00:00 IST 2015 : Job Executed..!! Bschedularv2.2
Sun Jul 05 06:00:00 IST 2015 : Job Executed..!! Bschedularv2.2
java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@160.xxx.67.xxx:1521/test
So, you can see, It failed on 3rd of July and 5th July as well. But, in between it ran fine.
View Replies
View Related
May 25, 2012
I am trying to use a custom listener to initialize database connection pool (C3P0) on start up and then destroy on context shut down. The reason for that is that I whenever context is shutdown I have a memory leak because initialized connection pool is not being destroyed.
I have a static class called C3P0Utils that deals with connection pool. In my listener in contextInitialized method I have tried at first to init the pool like this :
+public void contextInitialized(ServletContextEvent sce) {+
+try {+
C3P0Utils.newInstance().init();
+} catch (PropertyVetoException ex) {+
Logger.getLogger(DatabaseInit.class.getName()).log(Level.SEVERE, null, ex);
+}+
+}+
I know that object is created. I checked it using jconsole. However it is not accessible with in the application. My second attempt was to regester the pool and then add it to the context and then when I need it read from there.
+public void contextInitialized(ServletContextEvent sce) {+
+try {+
ServletContext ctx=sce.getServletContext();
C3P0Utils.newInstance().init();
ctx.setAttribute("myDataSource", C3P0Utils.newInstance().getDataSource());
+} catch (PropertyVetoException ex) {+
Logger.getLogger(DatabaseInit.class.getName()).log(Level.SEVERE, null, ex);
+}+
+}+
However when I try to red from the context I get nothing. I try to read like this.
+(ComboPooledDataSource)ctx.getAttribute("myDataSource")+
When I print names of all of the attributes in the context I get these attributes.
Context Name
org.apache.tomcat.InstanceManager
org.apache.catalina.jsp_classpath
javax.servlet.context.tempdir
org.apache.catalina.resources
+org.apache.tomcat.JarScanner
+org.apache.jasper.compiler.TldLocationsCache
+org.springframework.web.context.WebApplicationContext.ROOT
Why I can not use anything initialized in the listener.
View Replies
View Related
Jun 19, 2014
We have a J2EE business web application that runs in WebLogic. We noticed in application log files errors messages that seems like "No resource available in db pool", it means all the connection objects (to Oracle database) are used. Then the application is unstable and unseable.
I think the maximum number of connections configured in Weblogic pool has been reached due to an increase of users and activity. But when the workload decreases the application is still out of service. It seems connections objects are not relased to the pool. What can be the explanation for this issue ? Normally it is managed by the container (EJB3 for the business tier).
Once the limit of the pool is reached it is necessary to restart the server to solve this kind of error ?
View Replies
View Related
Sep 1, 2014
I have created a JSP page, on click of a particular button, the control moves to the servlet "TestServlet".
This is the code under TestServlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
[Code]...
Now, I have got a comment saying I should get the database connection from connection pool. And one more issue is that I have used the function System.getProperty("user.name") to get the username which i have logged in. But this code will be run on Unix which will not support this function. Any function where I can get the windows username. There is a function getUserPrincipal(), but this function returns a NULL. How to resolve this.
View Replies
View Related
Jan 11, 2015
I configured a connection pool in tomcat 7. For every database activity I get a connection from the pool. Do I have to close the connection like other regular connection after the database operation is done? If I close the connection will it have any effect on the connection pool?
View Replies
View Related
Dec 14, 2014
I have a Stock Database query class, it compiles and runs well. Thing is when i enter a user, it shows a user stock information but it repeats showing the same user in the command prompt. the repetition is so fast, you can't see the information. All i wanted was the application to show a user's info, then asks you to enter another user again and so forth. Here is the code
import java.io.*;
import java.sql.*;
import java.util.*;
public class StockDatabaseQuery {
public static void main(String[] args)throws Exception {
String userID;
String firstName;
[Code] ....
View Replies
View Related
May 11, 2014
how to give URL Connection to this?
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
public class WebBrowser
[code]....
View Replies
View Related
Oct 3, 2014
I am new to EJB; I am writing EJB (3.1) program in JBoss 7.1 - I am using MySQL DB with JPA. While executing the program, I am facing the Generic JDBCException: Could not open connection. It is happening only for certain tables in the database; but NOT for all tables. My code is able to access few of the tables in the same database. Here is my full stack trace: -
Exception in thread "main" javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection
at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleExceptionInOurTx(CMTTxInterceptor.java:166)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:230)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:304)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:190)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
[code]....
View Replies
View Related
Mar 9, 2015
package com.dnex;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
[code]....
I am getting the connection time out error in below line :-
System.out.println("response code"+httpConnection.getResponseMessage());
Note:-I need to pass user id and pwd in header parameter.and I am using https connection.
View Replies
View Related
May 13, 2014
I got the below exception .how to resolve this .It's receiving the data up to 10 min then suddenly below error happening. I have embedded the source code below
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
[Code] .....
View Replies
View Related
Nov 16, 2014
I am unable to connect my javafx scene to mysql database. I get a java.lang.NullPointerException every time. I tried searching everywhere possible but no answers available. This is the Person class (super class for Teacher class):
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
[code].....
View Replies
View Related
Jul 27, 2014
Below is a code of a simple file downloader in java. I want to detect an exception when the connection is broken in the middle of downloading a file. Now, I run the code and in the middle of downloading the file, i turn off my wifi with keyboard wifi off button. Doing this the program hangs forever without throwing any exceptions and without terminating. It seems it blocks forever.why is exception not thrown? Secondly, in the following code you can see this line //con.setReadTimeout(2000); which is currently commented out. Removing the comment and running the program, now if connection breaks in the middle by turning off wifi then it waits for 2 seconds and then if it cannot read then it terminates without throwing exception. So, again in this case why is it just terminating and not throwing any exception?
Java Code:
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.*;
[code]...
View Replies
View Related
Aug 5, 2014
I tried to connect oAuth2 with gmail. In command line, no problem. But with Javamail it failed.
The source of the exemple are here : [URL] ....
Last modified is in 2012 then, maybe, this code is obsolete.
In command line it works fine :
Java Code:
openssl s_client -crlf -connect imap.gmail.com:993
A002 AUTHENTICATE XOAUTH2
+
my_token_who_end_with__
Response : A002 OK myaddress@gmail.com ForName Name authenticated (Success) mh_sh_highlight_all('java');
For information :
- it failed with token and refresh token
- here are the logs :
Java Code:
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
[Code] ...........
View Replies
View Related
Jun 25, 2015
What I have in my tnsnames.ora and verify it all works via sqlplus
CDB1 =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = cdb1)
[Code] ....
I am trying to get RJDBC to work so I can connect to Oracle from R doing some data analysis..
This connection string works for my local db which I have it running in my Virtual Box
con <- dbConnect(drv, "jdbc:oracle:thin:@//localhost:1521/orcl", "demo", "demo")
However, it does not work when I do it for the remote db that I really need to pull data from...
> con <- dbConnect(drv, "jdbc:oracle:thin:@//ymsdbppr-scan:1522/YMQCTPRD", "user_read", "user_read")
Error in .jcall(drv@jdrv, "Ljava/sql/Connection;", "connect", as.character(url)[1], :
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12514, TNS: listener does not currently know of service requested in connect descriptor
View Replies
View Related
Feb 16, 2013
I have noticed an error, that makes sometimes troubles, when downloading jars from https addresses, when there are many jars to download..
Best example is by opening Javas on Java version checker. [URL] ....
I get also following log...
network: Connecting https://www.java.com/jsp_utils/jreverification.jar with proxy=DIRECT
network: Connecting http://www.java.com:443/ with proxy=DIRECT
network: Connecting https://www.java.com/jsp_utils/jreverification.jar with cookie "JSESSIONID=22ABBA2BE9B5789629C276AC35BDF969; s_cc=true;
Even if the address is https, java try to access via http protocol on port 443, and that leads sometimes to problems..
I have noticed this, when I have used URLConnection(HttpURLConnection) for my self, as soon Java sends http link on https address, the jar gets sometimes not loaded, and i get error about missing class that get called..
On http addres it is not so bad, since same protocol is used, but evidently, that is evil for https..
As you see, that happens already when loading Jar by Applet Starter and at all, it happens each time on any URLConnection
###############################
Java Plug-in 10.13.2.20
Using JRE version 1.7.0_13-b20 Java HotSpot(TM) Client VM
User home directory = X:Usersadmin
----------------------------------------------------
c: clear console window
f: finalize objects on finalization queue
g: garbage collect
[Code] .....
View Replies
View Related
Aug 21, 2014
I have failed with all possibilities that I know to make this program success. Getting error as :
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Program goes like this.
import java.sql.*;
public class ExcelConnection {
public static void main (String[] args){
try {
Connection conn = getConnection("TEST.xls");
Statement stmt = conn.createStatement();
[Code] ....
View Replies
View Related
Mar 1, 2014
I have a https connection from Client to Server and a malware in client. The malware modifies the message and compromises its integrity. I am using a proxy to check the Integrity of the message after the malware has changed the message and before sending it over the internet to the server.
Now, How can I check the Integrity of the message (Sure that it has not been modified by any Man in the Middle) for the second half of my communication channel(Which is from Client to the Server over the internet).
I see few conventional approaches of CRC or Checksum will work. But I am looking for some non traditional or upcoming approaches.
Ideally SSL Data shouldn't be able to be decrypted by any MIM. But my assumption is that any Protocol is subjected to attack and compromised in real world and few recent studies are proving that https is breakable. Thus, I am trying to perform a What if analysis? On the client side, lets say malware is not more powerful than just modifies the transaction amount and destination account number in a typical online Baking transaction.
View Replies
View Related
Oct 14, 2014
I have created a sample java web service client using Apache Axis. It works well with basicHTTPbinding (without security and Basic authentication).I am not able to make a secured communication. How to make it work in a secured way using NTLM or any other security.
View Replies
View Related
Dec 30, 2014
I am trying to connect to an oracle rac using jdbc thin . when i use the scan as the host, like this
String url = "jdbc:oracle:thin:@//<scan>:port/servicename;
I get error 1153, connection refused
but when i use the ip of the rac instead of the scan
String url = "jdbc:oracle:thin:@//<ip>:port/servicename;
The connection is successful
Is the issue at the application level? or is the problem with the server ....
View Replies
View Related