I have JBoss and MSSQL Server 2008. Sqljdbc.jar is in Java Resources/Libraries, but I still have a ClassNotFoundExeption.
This is my servlet :
package work.Model;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class SQLServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SQLServlet() {
super();
}
final String server = "localhost";
final int port = 1433;
final String user = "work";
final String password = "workdb";
final String database = "workDB";
final String jdbcUrl = "jdbc:sqlserver://"+server+":"+1433+";user="+user+";password="+password+";databaseName="+database+"";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println("try to load driver");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("# - Driver Loaded");
Connection con = DriverManager.getConnection(jdbcUrl);
System.out.println("# - Connection Obtained");
Statement stmt = con.createStatement();
System.out.println("# - Statement Created");
String loginCheck = "SELECT userID,username,password FROM USERS where username=? and password=?";
} catch (Exception ex) {
System.out.println("Error : "+ex);
}
}
}
The error is :
[STDOUT] Error : java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver from BaseClassLoader#724c0116{VFSClassLoaderPolicy#5bdb85f9{name=vfszip:/D:/Jboss/jboss-5.1.0.GA/server/default/deploy/Work.war/
How to correctly connect to MSSQL Server?
Try putting the SqlJdbc.jar in D:/Jboss/jboss-5.1.0.GA/server/default/lib folder and restart the server.
Servlets are used in the web application that has a predefined folder structure. As soon as you are not creating a deployment structure for JBoss server you have a chance to put JDBC driver jar to the WEB-INF/lib folder or copy it there during build.
Another approach is create a JBoss service that publish a datasource on JNDI and use its context and retrieve them on RAR deployment.
Related
My code to test db connection from eclipse is given below
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user="user01";
String pass="pass01";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC";
String driver = "com.mysql.cj.jdbc.Driver";
// get connection to database
try {
PrintWriter out = response.getWriter();
out.println("Connecting to database: " + jdbcUrl);
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
out.println("SUCCESS!!!");
myConn.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
am getting 404 error when i run this on server .I have added mysql-connector-java8.0.11.jar to lib folder of webinf.am using tomcat9 with java14 .
Normally, if you are getting a 404 error it means that the page is not found (Probably if your url isn't correct), if there is an error in the doGet Method "The connection to the database part" the server will respond with a 500 error.
https://www.codejava.net/java-ee/servlet/solved-tomcat-error-http-status-404-not-found
Let me know if that helped.
I am following the guide to connect from a java application using the IDE IntelliJ to an Oracle Cloud Database.
I meet the prerequisites since:
I have a Database in Oracle Cloud service
I downloaded the wallet and I placed the files in the src directory of my workspace.
I am using last JDK 14
I am using the ojdbc8.jar
And I downloaded as well the oraclepki, osdt_cert, and osdt_core jars, all of them added as java libraries in my test project
The recommended BD_URL is never working. I always get: java.net.UnknownHostException and oracle.net.ns.NetException: The Network Adapter could not establish the connection
DB_URL= "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=testgerard_high)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=testgerard_high)))"
Then I found in Oracle support that it could be added to the wallet directory, but the same issue.
DB_URL= "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=testgerard_high)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=testgerard_high))(SECURITY = (MY_WALLET_DIRECTORY = src\\Wallet_testGerard)))"
If I switch to a connection string using 18.3 JDBC driver which should work for my settings, then I get the error: Invalid connection string format, a valid format is: "host:port:sid"
DB_URL="jdbc:oracle:thin:#testgerard_high?TNS_ADMIN=src\\Wallet_testGerard";
Finally, I have seen here a way to inform the wallet folder out of the BD_URL so I do not get the invalid format exception:
System.setProperty("oracle.net.tns_admin","src\\Wallet_testGerard");
Now it is trying to connect but it fails after 60 seconds with the exception:sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
I adapted an oracle example, here is my code:
import java.sql.SQLException;
import java.sql.DatabaseMetaData;
import oracle.jdbc.pool.OracleDataSource;
import oracle.jdbc.OracleConnection;
public class OracleDataSourceSample
{
final static String DB_URL="jdbc:oracle:thin:#testgerard_high";
//final static String DB_URL="jdbc:oracle:thin:#testgerard_high?TNS_ADMIN=src\\Wallet_testGerard";
//final static String DB_URL= "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=testgerard_high)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=testgerard_high))(SECURITY = (MY_WALLET_DIRECTORY = src\\Wallet_testGerard)))";
final static String DB_USER = "hr";
final static String DB_PASSWORD = "hr";
public static void main (String args[]) throws SQLException, ClassNotFoundException {
System.setProperty("oracle.net.tns_admin","src\\Wallet_testGerard");
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleDataSource ods = new OracleDataSource();
ods.setURL(DB_URL);
ods.setUser(DB_USER);
ods.setPassword(DB_PASSWORD);
// With AutoCloseable, the connection is closed automatically.
try (OracleConnection connection = (OracleConnection)
ods.getConnection()) {
// Get the JDBC driver name and version
DatabaseMetaData dbmd = connection.getMetaData();
System.out.println("Driver Name: " + dbmd.getDriverName());
System.out.println("Driver Version: " +
dbmd.getDriverVersion());
System.out.println("Database Username is: " +
connection.getUserName());
}
}
}
Tested with stand alone jdk 8 and jdk 14 as well as Intellij Community edition(first run firewall blocked intellij).
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import oracle.jdbc.pool.OracleDataSource;
import oracle.jdbc.OracleConnection;
import java.sql.DatabaseMetaData;
public class SalesConnection
{
final static String DB_URL="jdbc:oracle:thin:#oci_adw_high";
final static String DB_USER = "xxxx";
final static String DB_PASSWORD = "xxxxx";
public static void main (String args[]) throws SQLException, ClassNotFoundException {
System.setProperty("oracle.net.tns_admin","C:\\app\\oracle\\product\\19\\dbhome_1\\network\\admin");
System.setProperty("oracle.jdbc.fanEnabled","false");
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleDataSource ods = new OracleDataSource();
ods.setURL(DB_URL);
ods.setUser(DB_USER);
ods.setPassword(DB_PASSWORD);
// With AutoCloseable, the connection is closed automatically.
try (OracleConnection connection = (OracleConnection)
ods.getConnection()) {
// Get the JDBC driver name and version
DatabaseMetaData dbmd = connection.getMetaData();
System.out.println("Driver Name: " + dbmd.getDriverName());
System.out.println("Driver Version: " +
dbmd.getDriverVersion());
System.out.println("Database Username is: " +
connection.getUserName());
printSales(connection);
}
}
public static void printSales(Connection connection) throws SQLException {
// Statement and ResultSet are AutoCloseable and closed automatically.
try (Statement statement = connection.createStatement()) {
try (ResultSet resultSet = statement
.executeQuery("select /* Java Console */PROD_ID, CUST_ID from sales fetch first 10 rows only ")) {
System.out.println("PROD_ID" + " " + "CUST_ID");
System.out.println("---------------------");
while (resultSet.next())
System.out.println(resultSet.getString(1) + " "
+ resultSet.getString(2) + " ");
}
}
}
}
Try to run this code change table and column names
Source of this code
Edit:
Compiling and executing from command prompt
javac -cp "C:\ojdbc8-full\*;" SalesConnection.java
java -cp "C:\ojdbc8-full\*;" SalesConnection
ojdbc8-full.zip contains oraclepki.jar, osdt_core.jar and osdt_cert.jar which are required for connecting to Oracle autonomous database. However, you can get JDBC driver along with other additional libraries using these maven co-ordinates.
<dependencies>
<dependency>
<groupid>com.oracle.database.jdbc</groupid>
<artifactid>ojdbc8-production</artifactid>
<version>19.7.0.0</version>
<type>pom</type>
</dependency>
</dependencies>
Refer to the Maven Central Guide for more information
I'm coding for hours to insert data into my SQL database, but nothing happens.
I even can't debug Java, because I don't get any output of my console.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author xxx
*/
public class MyServlet extends HttpServlet {
private static final String URL = "jdbc:mysql://localhost:3306/userdata";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static final DecimalFormat DF2 = new DecimalFormat("#.##");
private static Connection con;
private static Statement stmt;
private static ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
try {
String myDriver = "com.mysql.jdbc.Driver";
try {
Class.forName(myDriver);
// opening database connection to MySQL server
con = DriverManager.getConnection(URL, USER, PASSWORD);
// getting Statement object to execute query
// the mysql insert statement
String query = "INSERT INTO customers (customer, currency, amount) values ('Name', 'Currency', 100);";
stmt.executeUpdate(query);
// execute the preparedstatement
// executing SELECT query
rs = stmt.executeQuery(query);
con.close();
stmt.close();
rs.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
}
}
What did I wrong, that nothing happens? Even if I use this code for Java-Classes (not Servlets), I only receive an compile error, but without message.
I'm using the IDE Netbeans and mysql DB is the MySQL Workbench. The Java Class is using the main method.
Update:
I've tested following Code with IntelliJ:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/userdata";
String user = "root";
String password = "root";
String query = "Insert into customers (customer, currency, amount) values('Michael Ballack', 'Euro', 500)";
try (Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement(query)) {
pst.executeUpdate();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(JdbcMySQLVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
private static class JdbcMySQLVersion {
public JdbcMySQLVersion() {
}
}
I can insert data into the MySQL database.
In Netbeans this code won't work, although I've implemented the MySQLConnector. I don't know why, but Netbeans seems hard to handle.
In the servlet code, I don't see you ever write anything to out. So nothing is being sent back to the browser, even if it compiled. You could write your SQL exception to the out writer you created. To be more precise add this in your exception: out.println(sqlEx.printStackTrace()); That should at least show what exception you are getting back to the browser.
What is the compile error you get outside of a servlet?
This maybe obvious, but to get JDBC stuff to work on your server, you need to have the MySQL server installed, started and configured. The table referenced has to be defined, etc. You could check this outside of the Java servlet environment with the tools provided with MySQL.
your code can not compile, you miss catch exception for second 'try'.
Where do you use this class to run, if you run a java class, this class must contain main() function?
you should use some IDEs like eclipse or IntelliJ to code, it help you detect the error easier.
I found the solution. If you are using Netbeans with the Glassfish-Server and you want your servlet to save data into the database, you have to make sure that Netbeans has installed the Driver of your Database Connector (e.g. MySQL Connector). But you also have to configurate your server (e.g. Glassfish) which will support the DB Connector drivers.
In my case my Server didn't load the DB Connector Driver so the JDBC Code couldn't be executed.
Here's a useful link to configurate the Glassfish Server: https://dzone.com/articles/nb-class-glassfish-mysql-jdbc
I'm trying to establish a connection from Java to Oracle DB. (My DB is in another machine)
The form of URL as i know is like : String url = "jdbc:oracle:thin:#hostname:portnumber:sid";
And here is my Java code to establish a connection:
package net.metric.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text");
PrintWriter out = response.getWriter();
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//CONNECT TO DB
String url = "jdbc:oracle:thin:#252.112.60.47:1521:XE";
System.out.println(url);
Connection conn = DriverManager.getConnection(url,"EXT02501231","Tellcom30");
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
System.out.println("OK");
/* ResultSet rset =
stmt.executeQuery("select * from SBO_AUDIT_NEW.AUDIT_EVENT");
while (rset.next()) {
System.out.println (rset.getString(1));
}
stmt.close();
System.out.println ("Ok.");*/
}catch(Exception e){
System.out.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
I'm getting this error :
-------- Oracle JDBC Connection Testing ------
Io exception: The Network Adapter could not establish the connection
What am I doing wrong? Any answer would be appreciated..
Thanks
There are three ways to write to a jdbc url.
If you are connecting with service name you should put / before service name
jdbc:oracle:thin:#hostname:port/service_name --- In your case this is how you need the url
if you are connecting with sid you should put : before sid
jdbc:oracle:thin:#hostname:port:sid
or use the description in your tns file after #
jdbc:oracle:thin:#(DESCRIPTION=....)
BUT non of them are the cause for your problem. This error is not an SQLException. It is a TCP/IP connection exception. That means you somehow can not reach the machine.
Are you able to connect to the database with another client ? I see you are using TOAD. Are you able to connect with toad ? You need to make sure you can reach the server.
Try pinging to the machine on command line
ping 85.29.60.47
if you get response back then try telnet on the port
telnet 85.29.60.47 1521 -- You must have a telnet client installed to do that.
You will probably see either ping or telnet fails. So it is probably a firewall issue. What you need to do is to contact network administrators about the problem then.
Hi I am having some trouble while I am trying to access my database. The connection to the database is not getting established.
In the web browser I am getting the following output:
In Connection Db
In try before registering driver
null
Below is the code snippet I am using to establish the connection.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ConnectionDB extends HttpServlet {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Data";
// Database credentials
static final String USER = "root";
static final String PASS = "";
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
pw.println("<h2>In Connection Db</h2>");
try {
//STEP 2: Register JDBC driver
pw.println("<h2>In try before registering driver</h2>");
Class.forName("com.mysql.jdbc.Driver");
pw.println("<h2>In try</h2>");
//STEP 3: Open a connection
con = DriverManager.getConnection(DB_URL,USER,PASS);
pw.println("<h2>After connection</h2>");
stmt = con.createStatement();
My classpath variable is set as follows
CLASSPATH = C:\Database\mysql-connector-java-5.1.27\mysql-connector-java-5.1.27-bin.jar;
Thanks in advance.
You may want to specify the port number for the JDBC URL. For MySQL this is usually 3306. So, your JDBC URL should be:
jdbc:mysql://127.0.0.1:3306/Data
However, you may find that the root cause if because your mysql connector is not in the /WEB-INF/lib folder which participates in the webapp's runtime classpath. Just copy the JAR file straight in the directory /WEB-INF/lib and rebuild/redeploy/restart.
In addition, I assume that you are using a Java Application Server (as you are creating Servlets). Therefore, I would consider using a JDBC Connection Pool as an alternative.