SQLException - Connection reset error - sql-server-2008

I am trying to establish a jdbc connection with SQL Server 2008 R2, using the SQLJDBC4 jar file and JDK 1.6. I am using Netbeans IDE and have added the SQLJDBC4 jar and added the path to the database in the 'databases' section in the services. The code is as below:
package connect2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Connect2 {
public static void main(String[] args) throws SQLException {
Connection conn;
conn = null;
System.out.println("Done....");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection ("jdbc:sqlserver://172.17.39.13\\CRM:1433;databaseName=crm_xchanging","crm_xchanging","Welcome001");
System.out.println ("Database connection established");
}
catch (ClassNotFoundException e)
{
System.out.println (e);
}
catch (SQLException ex)
{
System.out.println(" error");
}
finally
{
if (conn != null)
{
try{
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM usertable");
System.out.println("User Name: " );
while (res.next()) {
String employeeName = res.getString("user_name");
System.out.println(employeeName);
}
conn.close();
}
catch(SQLException ex){
System.err.println("SQLException information");
while(ex!=null) {
System.err.println ("Error msg: " + ex.getMessage());
System.err.println ("SQLSTATE: " + ex.getSQLState());
System.err.println ("Error code: " + ex.getErrorCode());
ex = ex.getNextException();
// For drivers that support chained exceptions
}}
}
}
}
}
This is the output I'm getting:
run:
Done....
Database connection established
SQLException information
Error msg: Connection reset
SQLSTATE: 08S01
Error code: 0
BUILD SUCCESSFUL (total time: 1 second)
I don't think there is any mistake in the code or the JDK. I have also tried to set the max no. of active connections for SQL Server as 0 (infinite). How do I solve this problem?

There is a known bug introduced in Java 6u29 that causes SSL failure specifically with SQL Server 2008 R2. An Atlassian Fisheye troubleshooting page suggests a fix was incomplete.
Oracle delivered a fix in 6u30, although for at least one affected
client not even Java 1.7 worked.
On my development team we have found this bug to impact Java 8 at as well. One of the recommendation in the Fisheye article is to disable CBC protection using a JVM flag and that has also worked for me for SSL Java 8 SSL with a SQL Server 2008 R2 connection.
-Djsse.enableCBCProtection=false
The other suggestion is to revert to Java 1.6.0_24.

Related

Cordapp- Hikari Connection Pool class not found for MySql ConnectionPoolDataSource

I am building an workflow for Corda. I want to use the Hikari connection pool library for connecting to MySql database. I AM NOT trying to replace the, ledger H2 database. This database is for storing/retrieving some information, which is not needed in the ledger. I am able to connect to MySql WITHOUT Hikari. However when I use Hikari, I get an error.
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
I have tested the Hikari code, as a standalone jar file. It works fine. It is a combination of the way corda loads and runs the jar files, inside cordapps directory, which is causing the issue. Since the class is part of the jar. This seems it a little off
I have added the MySql dependency, inline with what is mentioned in https://docs.corda.net/cordapp-build-systems.html#setting-your-dependencies
I am also able to connect to the MySql DB, if I am not using Hikari.
I explored the cordapp jar .
And I could see that the requisite jar is present inside the cordapp jar.
Gradle dependencies for the cordapp
dependencies {
testCompile "junit:junit:$junit_version"
// Corda dependencies.
cordaCompile "$corda_release_group:corda-core:$corda_release_version"
cordaRuntime "$corda_release_group:corda:$corda_release_version"
testCompile "$corda_release_group:corda-node-driver:$corda_release_version"
runtime "mysql:mysql-connector-java:8.0.11"
cordaCompile "com.zaxxer:HikariCP:2.5.1"
// CorDapp dependencies.
cordapp project(":contracts")
}
Sample code
public class DataSource {
private static final Logger logger = LoggerFactory.getLogger(DataSource.class);
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;
static {
try {
logger.info("Connecting with connection pool datasource");
config.setDataSourceClassName("com.mysql.cj.jdbc.MysqlConnectionPoolDataSource");
config.addDataSourceProperty("useSSL", "false");
config.addDataSourceProperty("user", "username");
config.addDataSourceProperty("password", "password");
config.addDataSourceProperty("serverName", "localhost");
config.addDataSourceProperty("useSSL", "false");
config.addDataSourceProperty("port",Integer.parseInt("3306"));
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.addDataSourceProperty("requireSSL", "false");
config.addDataSourceProperty("serverTimezone", "UTC");
config.addDataSourceProperty("useServerPrepStmts", "true");
config.addDataSourceProperty("allowPublicKeyRetrieval", "true");
config.addDataSourceProperty("databaseName", "database");
config.setPoolName("Hikari-MySql Pool Name");
logger.error("-- Create Hikari Datasource with config {} --", config);
ds = new HikariDataSource(config);
} catch (Throwable t) {
logger.error("Error Occurred during Datasource Initializaiton", t);
throw t;
}
}
private DataSource() {
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
public class MySqlConnection {
static private final Logger logger = LoggerFactory.getLogger(MySqlConnection.class);
public Connection getMySqlConnection() {
Connection conn = null;
try {
conn = DataSource.getConnection();
logger.info("------------> Got conne :: " + conn);
} catch (SQLException e) {
logger.error("SQLException :: " + e);
}
return conn;
}
}
public class DataSourceTest {
static private final Logger logger = LoggerFactory.getLogger(DataSourceTest.class);
public static void main(String[] args) {
MySqlConnection mySqlConnection = new MySqlConnection();
Connection conn = null;
try {
conn = mySqlConnection.getMySqlConnection();
logger.info("------------> Got connection :: " + conn);
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("{some select statement}");
} catch (SQLException e) {
logger.error("SQLException :: " + e);
}
}
}
Exception:
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
at com.zaxxer.hikari.util.UtilityElf.createInstance(UtilityElf.java:90) ~[HikariCP-2.5.1.jar:?]
at com.zaxxer.hikari.pool.PoolBase.initializeDataSource(PoolBase.java:314) ~[HikariCP-2.5.1.jar:?]
at com.zaxxer.hikari.pool.PoolBase.<init>(PoolBase.java:108) ~[HikariCP-2.5.1.jar:?]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:99) ~[HikariCP-2.5.1.jar:?]
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:71) ~[HikariCP-2.5.1.jar:?]
If I run the code from a main class inside a jar, it works. But it does not work from inside a cordapp
In MySQL for HikariCP use setJdbcUrl instead of setDataSourceClassName
config.setJdbcUrl("jdbc:mysql://localhost:3306/simpsons");
The MySQL DataSource is known to be broken with respect to network timeout support. Use jdbcUrl configuration instead.
Check your dependency tree. I think you have some collision with "mysql-connector-java" dependency, which cause mess in class loader.

How to import MySQL using Gradle and connect into JavaFX

I'm using IntelliJ IDEA and JavaFX 10 for my practice learning. I want to connect MySQL and import it using Gradle.
I found multiple example in internet but I din't found any latest, most of the function is already depreciated and reading so much different example makes me confused.
You may want to read first the official documentation instead of reading multiple example.
I assume that you are beginner.
1.) First thing to do is to Download the MySQL Installer to intall the Server into your machine. Remember that things won't work without this.
During the installation you will need to set your Server PORT, root password or add a new user, just remember the Server PORT and root Password and leave things in default.
2.) Go to Maven Central. We need to import the MySQL Connector. In order to import the MySQL Connector into Gradle we need to get the correct group, name and version for it.
You notice that in Maven Central there are multiple selection on how you can import the jar into your project, this time we want to import it using Gradle,
so you have to choose the Gradle and copy the code: compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.11'
NOTE - In order to avoid problems, just always choose and use the latest version of MySQL Installer and MySQL Connector, at the moment the latest version is 8.0.11.
3.) In IntelliJ IDEA, in order to import in Gradle, in your project there is build.gradle click it to open then paste the code you copied in dependencies.
it should look like:
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.11'
}
4.) Create a class where you want to connect into MySQL, the below code is my example.
Main.Class
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args){
Connection conn = null;
String user = "whatEverUserNameYouSetup";
String password = "whatEverPasswordYouSetup";
String database = "whatEverTheNameOfYourDatabase";
int port = 3306; //default port, change it depending on your setup
try {
Class.forName("com.mysql.cj.jdbc.Driver").getConstructor().newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:" + port + "/" + database, user, password);
// Do something with the Connection
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
NOTE: The documentation is your friend.
UPDATE: If you run on error something like
Wed Dec 09 22:46:52 CET 2015 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
then you need to set useSSL to false, the code will be look like:
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Main {
public static void main(String[] args){
Connection conn = null;
Properties properties = new Properties(); //I use Properties to make things easer.
properties.setProperty("user", "root");
properties.setProperty("password", "YourPassword");
properties.setProperty("useSSL", "false"); //Set useSSL to false to solve the problem.
try {
Class.forName("com.mysql.cj.jdbc.Driver").getConstructor().newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306", properties);
// Do something with the Connection
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

sql server 2012 DTSPackage Config File Exception

I have a dtspackage which is executed through the C# coding.Earlier we have used sql server 2008 r2, Now we have moved to sql server 2012. The package was working fine with sql server 2008 while executing through C#code.But now while loading the Config file it throwing the exception like **
Microsoft.SqlServer.Dts.Runtime.DtsTaskException was caught
Message=Type mismatch. (Exception from HRESULT: 0x80020005
(DISP_E_TYPEMISMATCH)) Source=Microsoft.SqlServer.DTSRuntimeWrap
ErrorCode=-2147352571 StackTrace:
at Microsoft.SqlServer.Dts.Runtime.Package.ImportConfigurationFile(String
str)
**
public bool ExecuteDtsService()
{
bool retval = false;
StringBuilder strBldrErrorMsg = new StringBuilder();
Package pkg;
Application app= new Application();
DTSExecResult pkgResults;
ExecuteDTSEventListener eventListener = new ExecuteDTSEventListener();
try
{
String pkgLocation = objProcess.SSISFilePath + pathSpecifier + objProcess.JobName;
String pkLocationDtsConfig = objProcess.ConfigFilePath + pathSpecifier + objProcess.ConfigeFileName;
pkg = app.LoadPackage(pkgLocation, null);
pkg.ImportConfigurationFile(pkLocationDtsConfig); //getting error here
pkgResults = pkg.Execute();
if (pkgResults.ToString().Equals("Success"))
{
retval = true;
}
else if (pkgResults.ToString().Equals("Failure"))
{
foreach (DtsError local_DtsError in pkg.Errors)
{
strBldrErrorMsg.Append(local_DtsError.Description.ToString());
}
ReadLog(strBldrErrorMsg.ToString());
}
return retval;
}
catch(Exception ex)
{
objUtility.WriteLogFile(ex, "ExecuteDTSservice");
return retval;
}
}
The DTS package will download the xml content and transform to table.And it download one excel file and fetch the data from the excel.
The package running successful when i execute through the Execute Package Utility
Please guide me to fix the issue.
Thanks In Advance

Access to MySQL using Java Servlet?

The Solution:
I added this code
Class.forName("com.mysql.jdbc.Driver");
brfore
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
Thank you all for reply my question
====================
I have problem, I try to insert data into mysql db using servlet, but I couldn'y access to MySQL
Database name: test
Table name: test
I already added jdbc connector to the project library
I'm using JDK 1.7, NetBeans 7.3, MySQL 5.6, Tomcat 7.0, Connector/J 5.1.24
1- this is "form action" in sign_up.jsp page:
<form action="RegisterUser" method="post">
<td><input type="submit" value="Submit"></td>
</form>
2- this is RegisterUser.java servlet:
import java.io.IOException;
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 com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
#WebServlet(urlPatterns = {"/RegisterUser"})
public class RegisterUser extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan3";
int phone = 123456;
String insert = "INSERT INTO test VALUES ('\" + name + \"', \" + phone + \")";
s.executeUpdate(insert);
s.close();
con.close();
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
3- the exception result:
HTTP Status 500 - Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
type Exception report
message Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.SecurityException: Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
RegisterUser.processRequest(RegisterUser.java:66)
RegisterUser.doPost(RegisterUser.java:173)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.39 logs.
4- But when I use same code but in java file "without servlet or web app" it's working correctly:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static void main(String[] args){
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan4";
int phone = 8985895;
String insert = "INSERT INTO test VALUES ('" + name + "', " + phone + ")";
s.executeUpdate(insert);
s.close();
con.close();
System.out.println("done");
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
}
so what is problem with servlet? Why the code works with java app. but it doesn't work with web app.?
You are getting Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
It means When you are running it from Web Application, JRE could not find Class in the Classpath.
If this code works in your Standalone it means you need to have a JAR file somewhere containing com.mysql.jdbc.Driver class (so called JDBC driver). This JAR needs to be visible in Tomcat. So, I would suggest placing mysql-jdbc.jar at a physical location to /WEB-INF/lib directory of your project.
Alternatively, you can add Third party libraries like JDBC driver here using
Right Click Project Name--> Properties
from your NetBeans IDE
Then restarting Tomcat should work.
Second, you don't need
import com.mysql.jdbc.Driver;
in your Servlet.
David is right and i want to add, you can also install the driver by pasting the jar file in the the installation folder of java.
\Program Files\Java\jre7\lib\ext
Well i dont like mysql very much and always use Mssql with a windows server 2008. This is the code i use for that, i might be your answer since mysql connection works pretty much the same as sql.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName="+database+";user="+user+";password="+password);
First, you should put that into a persistance layer.
1) Ensure that your JDBC driver is in place. Copy it into your classpath, e.g. /WEB-INF/lib directory. Link: MySQL JDBC Driver Download Page
2) Check your connect string: jdbc:mysql://<server>:<port>/<database>, looks like the port is missing. Try jdbc:mysql://127.0.0.1:3306/test

jdbc connection of mysql to html

Hi i have the following file to connect mysql database to html files. But i am having trouble connecting it. Can anyone tell me where i find the locations.
What should i replace "jdbc:mysql://localhost/zulfiqar" with for it to work on my computer? where do i find this?
And is there anything else i have to change to make it work on my computer? this was a piece of code i found on the internet which i am trying to make work so i can understand how to do it, but i am struggling.
Thanks in advance!
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletUserEnquiryForm extends HttpServlet{
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
/**Process the HTTP Get request*/
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException{
String connectionURL = "C:\Program Files(x86)\MySQL Server 5.0\bin\mysql.exe";
Connection connection=null;
ResultSet rs;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//get the variables entered in the form
String uId = req.getParameter("userId");
String fname = req.getParameter("firstname");
String sname = req.getParameter("surname");
String address1 = req.getParameter("address1");
String address2 = req.getParameter("address2");
String town = req.getParameter("town");
String county = req.getParameter("country");
String zipcode = req.getParameter("zipcode");
try {
// Load the database driver
Class.forName("org.gjt.mm.mysql.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection
(connectionURL, "root", "admin");
//Add the data into the database
String sql =
"insert into emp_details values (?,?,?,?,?,?,?,?)";
PreparedStatement pst =
connection.prepareStatement(sql);
pst.setString(1, uId);
pst.setString(2, fname);
pst.setString(3, sname);
pst.setString(4, address1);
pst.setString(5, address2);
pst.setString(6, town);
pst.setString(7, county);
pst.setString(8, zipcode);
int numRowsChanged = pst.executeUpdate();
// show that the new account has been created
out.println(" Hello : ");
out.println(" '"+fname+"'");
pst.close();
}
catch(ClassNotFoundException e){
out.println("Couldn't load database driver: "
+ e.getMessage());
}
catch(SQLException e){
out.println("SQLException caught: "
+ e.getMessage());
}
catch (Exception e){
out.println(e);
}
finally {
// Always close the database connection.
try {
if (connection != null) connection.close();
}
catch (SQLException ignored){
out.println(ignored);
}
}
Some additional information about how it's failing might be useful.
1) Is it failing to make the socket connection (implying your service isn't running), or
2) Did it fail to initialize the driver? I'm not familiar with the one you listed. A more common alternative is "sun.jdbc.odbc.JdbcOdbcDriver".
3) Did you connect and simply fail authentication with user "root" and password "admin"?
What should i replace "jdbc:mysql://localhost/zulfiqar" with
Ans: It is the connection url. It does mean your MySQL database is running on localhost server (with default port) and you are connecting to 'zulfiqar' database. So first line under doPost() should be :
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Next, you are using org.gjt.mm.mysql.Driver driver for JDBC connection. It was initially developed by a hobbyist. It's later donated to MySQL where they renamed the package/classname. The old classname is kept for backwards compatibility reasons, but you should update it to com.mysql.jdbc.Driver and add mysql-connector-java-*-bin.jar in your WEB-INF/lib folder.
Next thing you are using :
connection = DriverManager.getConnection(connectionURL, "root", "admin");
So you are loading a connection from the connectionURL and accessing it with root user and admin password. Make sure these are correct in your case.
Last point is, you are inserting into emp_details table. Make sure you have this table already created in zulfiqar database with all required columns. And the number of '?' marks in the sql string should match the number of times you are doing pst.setString(index, data), otherwise you will get Invalid parameter index error.