ERROR MESSAGE in SERVER
[2019-01-07 09:44:02] ERROR
:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications
link failure
[2019-01-07 09:44:02]
[2019-01-07 09:44:02] The last packet sent successfully to the server was 0
milliseconds ago. The driver has not received any packets from the server.
But testing in local.. No problem.. No Error message..
Commit libraries..
mysql-connector-java-5.1.47-bin.jar
mysql-connector-java-5.1.47.jar
JDBC URL ALTER
jdbc:mysql://IP:3306/ID -> jdbc:mysql://IP:3306/ID?autoReconnect=true
Changed Error Message..
[2019-01-07 11:04:32] Error :
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could
not create connection to database server. Attempted reconnect 3 times.
Giving up.
ControlDAO.java
private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String URL =
"jdbc:mysql://IP:3306/ID?autoReconnect=true;
public static void CsNumberCheck(String s) {
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, "ID", "PW");
System.out.println(conn);
stat = conn.createStatement();
int result = 0;
sql = Query;
rs = stat.executeQuery(sql);
while ( rs.next() ) {
result = rs.getInt(1);
}
rs.close();
stat.close();
System.out.println(result);
CsNumberResult(result, OrangeEmail);
}
catch (ClassNotFoundException e) {
System.out.println("Driver Loading Failed..");
}
catch (SQLException e) {
System.out.println("Error : " + e);
}
}
Socket.java
ControlDAO.CsNumberCheck(s);
But nothing result about "Sysout", Only Error Message....
Check your windows services to see if your MySQL server is running. That might be a probable cause. If it's not, start it and try to reconnect.
Related
I´m using eclipse and want to connect to my mysql database. I am new to SQL and thats my first time I want to do something like this. I´ve created two methods, which should connect to a mysql database, which is running on my PC. The first method should create a connection :
public static Connection connectionSQL() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/example";
String username = "example";
String password = "1111";
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("Connected!");
} catch(SQLException | ClassNotFoundException e) {
System.out.println("ERROR: Cant connect to database! "+ e);
}
return null;
}
the second should create a table :
public static void createTable() {
try {
Connection connection = connectionSQL();
PreparedStatement ps = connection.prepareStatement("CREATE TABLE IF NOT EXISTS scammerjail(id int NOT NULL AUTO_INCREMENT, Username String, Countdown int, PRIMARY KEY(id))");
ps.executeUpdate();
} catch(SQLException e) {
System.out.println("ERROR: Cant create Table! " + e);
}
finally {
System.out.println("Table created!");
}
}
But everytime I try to run my Code, I get the following message:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client
I´m using maven as build tool and my dependency and its version isnt wrong I think.
I'm getting the following error:
I tried various ways I'm getting an error please see the following error.
run: java.lang.ClassNotFoundException:
com.microsoft.sqlserver.jdbc.SQLServerDriver at
java.net.URLClassLoader.findClass(URLClassLoader.java:381) at
java.lang.ClassLoader.loadClass(ClassLoader.java:424) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) at
java.lang.ClassLoader.loadClass(ClassLoader.java:357) at
java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Class.java:264) at
com.sqldbsamples.App.main(App.java:23)
BUILD SUCCESSFUL (total time: 0 seconds)
This is my code: please help me with how to connect my database to azure using java program !!!
public class App {
public static void main(String[] args) {
// Connect to database
String hostName = "testchinnaa.database.windows.net:1433"; // update me
String dbName = "Test_Gopi"; // update me
String user = "chinna"; // update me
String password = "******"; // update me
String url = String.format("jdbc:sqlserver://testchinnaa.database.windows.net:1433;database=Test_Gopi;user=chinna#testchinna;password=*****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"
+ "hostNameInCertificate=*.database.windows.net;loginTimeout=30;", hostName, dbName, user, password);
Connection connection = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url);
String schema = connection.getSchema();
System.out.println("Successful connection - Schema: " + schema);
System.out.println("Query data example:");
System.out.println("=========================================");
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName "
+ "FROM [SalesLT].[ProductCategory] pc "
+ "JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectSql)) {
// Print results from select statement
System.out.println("Top 20 categories:");
while (resultSet.next())
{
System.out.println(resultSet.getString(1) + " "
+ resultSet.getString(2));
}
connection.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Sorry, you have to figure out if you are using MySql or MSSql. You said that you used mysql. However, in your connection string, it is a sqlserver which means it is a MSSql.
Here is the tutorial for accessing database using java:
You need to download connector for your database:
For MySql: MySQL
Connector/J
For MSSql: Microsoft JDBC Driver for SQL
Server
Manually add connector jar file to your classpath. Or you can use Maven dependencies manager to install and configure the Connector/J library in your project.
<!-- Example for mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
Code sample
For MSSql:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
connection = DriverManager.getConnection("conntection_string");
String SQL = "SELECT name FROM sysdatabases;";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SQL)) {
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
For MySql:
Connection conn = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connectionUrl = "jdbc:mysql://{server_name}.mysql.database.azure.com:3306?useSSL=true&requireSSL=false&serverTimezone=UTC";;
conn = DriverManager.getConnection(connectionUrl, "username_from_portal, like: jack#mysqldemo258", "password");
rs = conn.prepareStatement("show databases").executeQuery();
while(rs.next()){
System.out.println(rs.getString(1));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try{
if(rs != null) rs.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
I am trying to connect a simple Java code with PostgreSQL database on Heroku. I have tried everything as needed, but I am getting the following error:
org.postgresql.util.PSQLException: The connection attempt failed.
I am not able to understand what is going wrong.
Following is the code I am using:
String dbUrl = "jdbc:postgresql://some-text.eu-west-1.compute.amazonaws.com:5432/some-text?ssl=true&sslmode=require";
String username = "some-text";
String password = "some-text";
try {
Class.forName("org.postgresql.Driver");
} catch (Exception e) {
System.out.println("Failed: " + e.toString() + e.getMessage());
}
try {
Connection connection = DriverManager.getConnection(dbUrl,username,password);
Statement statement = connection.createStatement();
String query = "select * from table";
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()){
System.out.println(resultSet.getString("column"));
}
} catch (SQLException e) {
System.out.println(e.toString());
}
I would appreciate if someone could help me with this.
So i am facing the following problem.
I have developed an web app that has the following connection to a SQL Server database. (db connection code attached)
public class DBConnection
{
private DatabaseMetaData dma;
private static Connection con;
private static DBConnection instance = null;
private static String security = "integratedSecurity=true;";
private DBConnection()
{
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} catch (Exception e) {
System.out.println("Can not find the driver");
System.out.println(e.getMessage());
}
try{
con = DriverManager.getConnection("jdbc:jtds:sqlserver://<Machine>;databaseName=<DBName>; useNTLMv2=true;");
//set autocommit
con.setAutoCommit(true);
dma = con.getMetaData(); // get meta data
System.out.println("Connection to " + dma.getURL());
System.out.println("Driver " + dma.getDriverName());
System.out.println("Database product name " + dma.getDatabaseProductName());
}
catch(Exception e){
System.out.println("Problems with the connection to the database");
System.out.println(e.getMessage());
System.out.println(con);
}
}
public static void closeConnection()
{
try{
con.close();
System.out.println("The connection is closed");
}
catch (Exception e){
System.out.println("Error trying to close the database " + e.getMessage());
}
}
public Connection getDBcon()
{
return con;
}
public static DBConnection getInstance()
{
if (instance == null)
{
instance = new DBConnection();
}
return instance;
}
public static void startTransaction()
{ try{
con.setAutoCommit(false);
}
catch(Exception e){
System.out.println("fail start transaction");
System.out.println(e.getMessage());
}
}
public static void commitTransaction()
{ try{
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail commit transaction");
System.out.println(e.getMessage());
}
}
public static void rollbackTransaction()
{
try
{
con.rollback();
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail rollback transaction");
System.out.println(e.getMessage());
}
}
I am using a Tomcat 8 on InteliJ IDE for running the app and debugging. Which works fine. (DB connection is established)
The problem is that when i take the war file and deploy it in the same Tomcat Server i get no DB Connection. (No DB connection)
I have checked all the .jar files in the tomcat and the project and I have added all the needed files.
Can't seem to find what is causing this issue. Maybe there is someone who got stuck with the same issue
I can't get a proper undertanding what is causing this issue and how to fix it
**EDIT: Following I have added the error displayed when trying to load data
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is java.lang.NullPointerException
root cause
java.lang.NullPointerException
com.lifeletapp.business.dataLayer.DbLogIn.isValidUser(DbLogIn.java:27)
com.lifeletapp.business.HelloController.verifyLogin(HelloController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
DbLogin class:
public class DbLogIn implements ILogIn
{
private Connection conn;
public DbLogIn()
{
conn = DBConnection.getInstance().getDBcon();
}
public Staff isValidUser(String userName, String password)
{
Staff staff = new Staff();
try {
String query = "SELECT * FROM Staff WHERE userName=? AND pass=?";
PreparedStatement preparedStatement = conn.prepareStatement( query );
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
while( resultSet.next() ) {
staff.setUserID(resultSet.getInt("userID"));
staff.setfName(resultSet.getString("fName") );
staff.setlName(resultSet.getString("lName") );
staff.setUserName(resultSet.getString("userName") );
staff.setPass(resultSet.getString("pass") );
staff.setEmail(resultSet.getString("email") );
}
resultSet.close();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return staff;
}
}
This is more a config or server issue. Not a code issue.
As mentioned in the comments I have tested if var conn == null -> resulted true. And the connection dose not get nulled anywhere. Please view code. Then again the above code works when run from the InteliJ debugger.
So finally figured out what was the issue.
Why was it working on my IDE config:
1. I was using java JDK 1.7 as JAVA_HOME
2. I was using an older version of Tomcat as a build
3. In order to work with JDTS you need to extract the nlmauth.dll from the .jar archive and copy it to the configured env JDK(jdk1.7-->>bin->>copy here)
Why was it not working on Tomcat server:
1.I was using Tomcat 8.xxx
2.Tomcat 8.xx require JDk 8
3. In the JDK 8 i have not past the nlmauth.dll ( once i have done this everything was working)
In order to approach this issue the first clue will be looking into the tomcat server logs.
On my presumption this issue is prom to occur only when you have an Database connection establish via Integrated Security.
My presumption is related to the fact that in the tomcat log the main error that was denying the JDBC driver was based on the integrated security credentials.
Best of luck to you all out there.
I'm trying to connect to mysql database from my android application.
I'm getting Communications link failure error.Below is the code snippet:
public class MySqlConnector {
private Connection con = null;
private String s = "";
private String username = "root";
private String password = "password01";
private String connectionString;
public String ConnectToDb() {
connectionString ="jdbc:mysql://192.168.1.104:3306/mydatabase";
//connectionString="jdbc:mysql://10.0.0.0:3306/mydatabase";
// connectionString="jdbc:mysql://127.0.0.1:3306/mydatabase";
//connectionString = "jdbc:mysql://MainSrv04:3306/mydatabase";
// connectionString="jdbc:mysql://localhost:3306/mydatabase";
// connectionString =
// "jdbc:mysql://localhost:3306/mydatabase?user=root&password=password01&useUnicode=true&characterEncoding=UTF-8";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
con = DriverManager.getConnection(connectionString, username,
password);
Statement st = con.createStatement();
String sql = "SELECT First_Name FROM mydatabase.custinfo where CardNumber=5325784707";
ResultSet rs = st.executeQuery(sql);
s = rs.getString("First_Name");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
Log.i("MySqlConnector", "Database connection terminated");
} catch (Exception e) { /* ignore close errors */
}
}
}
if (s == "") {
s = "No Result";
}
Log.i("MySqlConnector : s=", s);
return s;
}
}
I tried all possible combinations as showed in comments and getting following error in caused by field in logcat:
while using localhost --> Caused by: java.net.ConnectException: localhost/127.0.0.1:3306 - Connection refused
while using 127.0.0.1 --> Caused by: java.net.ConnectException: /127.0.0.1:3306 - Connection refused
while using 10.0.0.0 --> Caused by: java.net.SocketException: The operation timed out
while using 192.168.1.104 --> Caused by: java.net.SocketException: The operation timed out
while using MainSrv04 --> Caused by: java.net.UnknownHostException: MainSrv04
I also pinged mysql port through telnet and it's working.
Also, I have taken care of privileges.
But still I'm getting Communications link failure error.
Any help appreciated.
Is android application is on same ntework? If not
jdbc:mysql://192.168.1.104:3306
and
jdbc:mysql://10.0.0.0:3306
will not work.
Give the proper network address of mysql.
I use latest version of adt and mysql-connector-java-5.1.17-bin.jar, this works for me :
Add the below code into your file after the line setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
and use import android.os.StrictMode;
If you use new api, add #SuppressLint("NewApi");