errors while try to run executeQuery/prepared statements() - java

SQL statement is not executedcom.mysql.jdbc.CommunicationsException: Communications link >failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException MESSAGE:
Connection refused
STACKTRACE:
java.net.ConnectException: Connection
refused at
java.net.PlainSocketImpl.socketConnect(Native
Method) at
java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:310)
at
java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:176)
at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:163)
at
java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at
java.net.Socket.connect(Socket.java:546)
at
java.net.Socket.connect(Socket.java:495)
at
java.net.Socket.(Socket.java:392)
at
java.net.Socket.(Socket.java:235)
at
com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at
com.mysql.jdbc.MysqlIO.(MysqlIO.java:271)
at
com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at
com.mysql.jdbc.Connection.(Connection.java:1555)
at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at
java.sql.DriverManager.getConnection(DriverManager.java:620)
at
java.sql.DriverManager.getConnection(DriverManager.java:200)
at
org.jtdemo.preparedst.main(preparedst.java:18)
** END NESTED EXCEPTION **
Last packet sent to the server was 1
ms ago. at
com.mysql.jdbc.Connection.createNewIO(Connection.java:2847)
at
com.mysql.jdbc.Connection.(Connection.java:1555)
at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at
java.sql.DriverManager.getConnection(DriverManager.java:620)
at
java.sql.DriverManager.getConnection(DriverManager.java:200)
at
org.jtdemo.preparedst.main(preparedst.java:18)
My program is
package org.jtdemo;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class preparedst
{
//private static final String y = null;
public static void main(String arg[])throws Exception
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3036/mylib_db";
Connection con=DriverManager.getConnection(url,"nikki","dkm007");
String query = " select c.sub_category, b.title,b.author,b.b_key,ta.available_copies" +
"from Book_dim b,Category_list c,item_availablity_fact ta" +
" where sub_category = 'Mathematics' and " +
" c.category_id=b.category_id and " +
" b.b_key=ta.b_key " ;
/*ps = con.prepareStatement(" select c.sub_category, b.title,b.author,b.b_key,ta.available_copies" +
"from Book_dim b,Category_list c,item_availablity_fact ta" +
" where sub_category = ? and " +
" c.category_id=b.category_id and " +
" b.b_key=ta.b_key ");*///pass sql query ,no parameter passing
//ps.String(1, "Mathematics"); // set input parameter
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query) ;
while(rs.next())
{
String scat = rs.getString(1);
String ttl = rs.getString(2);
String auth = rs.getString(3);
int bkey = rs.getInt(4);
int avcop = rs.getInt(5);
//String b_key;
System.out.println("subcategory:"+scat+"title:"+ttl+"author:"+auth+"bookkey:"+bkey+"availcopies:"+avcop);
}
con.close();
//ps.close();
}
catch(Exception e)
{
System.out.println("SQL statement is not executed");
e.printStackTrace();
}
}
}
i am using jdk 1.6,mysql-connector-java-5.0.8-bin.jar,Eclipse Version: 3.5.2.
Please help.................

The exception tells you the problem. If your connection was refused, then there is something wrong with either the configuration of the client or the server. So the first thing to check is the JDBC URL. You need to verify the following:
The server is at localhost
The server is serving on port 3036 (the default port for MySQL is 3306, so this may be your problem)
You have a database on that server named 'mylib_db'
Your user name is correct
Your password is correct (in the future you may want to use placeholder text like 'password')
If all that information is correct, you need to examine your server to ensure that 'nikki' has permission to connect to the database over the network.

It looks like a network problem. It seems the database is not listening on the port you're telling java to connect to.
I would check that the port is indeed listening (via netstat), check any anti-virus, firewall, security programs, etc. If this all comes back good then perhaps a restart of your database program (myssql) would do the trick.

Related

Issues with username and password when connecting to oracle database 12c through ojdbc

I have SQL developer installed and a properly configured DB, I create a user from sys like so:
CREATE USER random IDENTIFIED BY 12345;
GRANT ALL PRIVILEGES TO random;
I attempt to connect to the oracle SQL database with the ojdbc8.jar found in oracles website like this:
String url = "jdbc:oracle:thin:random/12345#localhost:1521:home";
try{
Connection dbConn = DriverManager.getConnection(url);
}catch(Exception e){
System.out.println("Exception: " + e.getLocalizedMessage());
}
However I receive this error:
Exception: ORA-01017: invalid username/password; logon denied
The last time I asked this question it was just populated by answers that have no actual answer to the problem at hand, I don't need to change the driver to a different one, I don't need to instantiate some sort of factory nonsense that just adds complexity, all I want to know is how I'm meant to connect to an account that is part of my DB so I can perform basic SQL functions.
Edit:
It just occurred to me that it is a pdb, is there a modification needed to the connection url that anyone can point out?
Try:
Connection dbConn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:home", "random", "12345");
PDB connections need a slight tweak.
Please use localhost:port/sid instead of localhost:port:sid:
if (isPluggableDB) {
conn = DriverManager.getConnection("jdbc:oracle:thin:#" + hostName + ":" + hostPort + "/" + sid, userName, password);
} else {
conn = DriverManager.getConnection("jdbc:oracle:thin:#" + hostName + ":" + hostPort + ":" + sid, userName, password);
}

AWS Lambda connecting to publicly accessible AWS RDS

I created a publicly accessible PostgreSQL RDS in AWS and have the following code to connect to it:
try {
DriverManager.registerDriver(new org.postgresql.Driver());
String url = "jdbc:postgresql://" + DATABASE_SERVER_NAME + ":" + DATABASE_PORT_NUMBER + "/" + DATABASE_NAME + "?user=" + DATABASE_USER + "&password=" + DATABASE_PASSWORD;
try (Connection connection = DriverManager.getConnection(url)) {
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM \"" + PHANTOM_LOAD_STORE_DATABASE_TABLE_NAME + "\"")) {
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
System.out.println(resultSet.getString("userid"));
}
}
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
When this is run locally it connects to the database server successfully.
When this is run in an AWS Lambda it fails to connect with the following error:
org.postgresql.util.PSQLException: The connection attempt failed.
...
Caused by: java.net.SocketTimeoutException: connect timed out
The lambda is not in a VPC and has the role policy arn:aws:iam::aws:policy/AmazonRDSDataFullAccess.
Can someone tell me what I'm doing wrong?
Despite creating the RDS database to be publicly accessible it had a security group rule that only allowed incoming requests from my IP (the one that created the database). Editing its security group's incoming rules to allow requests from anywhere has allowed the lambda to connect to the database.
The policy arn:aws:iam::aws:policy/AmazonRDSDataFullAccess seems unnecessary.
Thanks to this answer for helping me work it out.

Java & MySQL can have debug log?

I'm using mysql to create a connection with my database. The code is working fine, but what if i enter a wrong username/pass/host/database can i get a log message with the part is wrong? Here is the code:
private void connectDatabase()
{
try {
connection = DriverManager.getConnection("jdbc:mysql://" + hostname + ":" + port + "/"
+ database + "?autoReconnect=true", username, password);
System.out.println("[MySQL] The connection to MySQL is made!");
} catch (SQLException e) {
System.out.println("[MySQL] The connection to MySQL couldn't be made! reason: "
+ e.getMessage());
}
}
Ex: I enter a wrong password and i get this error log:
[MySQL] The connection to MySQL couldn't be made! reason: Wrong password.
Is this possible?
For MySQL, you will get an SQLExcpetion, something like below:
Caused by: java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073) ~[mysql-connector-java-5.1.18.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609) ~[mysql-connector-java-5.1.18.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541) ~[mysql-connector-java-5.1.18.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:943) ~[mysql-connector-java-5.1.18.jar:na]
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:4113) ~[mysql-connector-java-5.1.18.jar:na]
...
SQLException will have SQLState = 28000, and vendorCode = 1045

Connecting to sybase using jdbc in solaris

I am trying to learn how to use jdbc.
Normally to connect to sybase db on solaris I use:
isql -Usa -Pxxxxxx -Dxxxxxx
its gets connected to the db by the above.and i can rightaway execute the queries.
Now i am trying to just do a similar thing using java.
below is my code.
public class SKRSample
{
public static void main(String args[])
{
try
{
Class.forName("com.sybase.jdbc.SybDriver");
}
catch (ClassNotFoundException cnfe)
{
System.err.println("Error loading driver: " + cnfe);
}
try
{
String host = "172.16.65.33";
String dbName = "bsmdb";
int port = 1234;
String url = "jdbc:sybase:Tds:" + host + ":" + port + ":" + "?SERVICENAME=" + dbName;
for (int n = 0; n<args.length; n++) {
if (args[n].equals("-u")) user = args[++n];
else if (args[n].equals("-p")) password = args[++n];
else throw new IllegalArgumentException("Unknown argument.");
}
Connection con = DriverManager.getConnection(url, user, password);//here is the error.
The last line of the code is where there is a runtime error.
i compiled the code and execueted as below:
setenv LOGIN "sa"
setenv PASSWORD "xxxxxxx"
javac SKRSample.java
java SKRSample -u $LOGIN -p $PASSWORD
the error i am getting is :
Unexpected exception : java.sql.SQLException: No suitable driver found for jdbc:sybase:Tds:172.16.65.33:1234:?SERVICENAME=bsmdb, sqlstate = 08001
i have a doubt that either the host is incorrect or the port is incorrect or the url i am framing is incorrect.how can get the host name if at all it is incorrect.and also how can get the port number if the problem lies there.
But i am not sure about the problem.Can anyone give me some head's up regarding where exactly the problem is there.
Seems that the JDBC url format is wrong.
the right format is jdbc:jtds:sybase://<host>[:<port>][/<database_name>]
You will have to download the driver and execute the class so that it uses the driver in the path specified by you.
You need to use proper JDBC driver and connection string together. For example, you can use "com.sybase.jdbc2.jdbc.SybDriver" (in jconn2.jar) and "jdbc:sybase:Tds:MyDbComputerNameOrIP:2638" together. Please check the following page for more options.
Sybase JDBC Driver and URL Information
In your code, it seems that you added extra ":" in the connection URL. Remote the ":" after port number. The following two connection URL should work with "com.sybase.jdbc.SybDriver".
String url = "jdbc:sybase:Tds:" + host + ":" + port + "?SERVICENAME=" + dbName;
or
String url = "jdbc:sybase:Tds:" + host + ":" + port + "/" + dbName;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
And use JTDS driver jar in the classpath
It may be a bit late, but still I had the same issue and spent much time investigating, so I'll put some outcome here:
1. We need to include the driver class in our code as well as java.sql:
import com.sybase.jdbc3.jdbc.SybDriver;
import java.sql.*;
2. We need to run javac with the path to the driver in the classpath (I have jconn3.jar here - /usr/local/localagent/jar/jconn3.jar):
javac -cp "/usr/local/localagent/jar/*" test_conn.java
3. We need to put the same classpath when running the class:
java -cp ".:/usr/local/localagent/jar/*" test_conn
My code for test_conn.java is below:
import com.sybase.jdbc3.jdbc.SybDriver;
import java.sql.*;
public class test_conn {
public static void main(String[] args) {
String host = "myhost";
String url = "jdbc:sybase:Tds:"+host+":4100";
String username = "username";
String password ="password";
String dbname ="dbname";
SybDriver sybDriver = null;
Connection conn;
try
{
sybDriver=(SybDriver)Class.forName("com.sybase.jdbc3.jdbc.SybDriver").newInstance();
System.out.println("Driver Loaded");
conn = DriverManager.getConnection( "jdbc:sybase:Tds:"+host+":4100?SERVICENAME="+dbname, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("sp_helpdb");
rs.next();
System.out.println(rs.getString(1));
conn.close();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
It worked for me, so I hope this helps.

Access Denied? Wrong user / pass

I'm trying to write a java program to connect to the same MySQL database my website uses. I am using the same login details, minus the hostname ofcourse, but I am getting these errors:
SQLException: Access denied for user 'USER'#'HOSTNAME' (using password: YES)
SQLState: 28000
VendorError: 1045
I am using the hostname my host provided, and the password and user are the same details I have on my website.
Here is the code snippit:
public main() {
Connection con = null;
String mysql_hostname = "HOST";
String mysql_username = "USER";
String mysql_password = "PASS";
String mysql_database = "DB";
int mysql_port = 3306;
initComponents();
try {
con = DriverManager.getConnection("jdbc:mysql://"+ mysql_hostname +":"+ mysql_port +"/"+ mysql_database +"?user="+ mysql_username +"&password="+ mysql_password);
}
catch(SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
This is probably to do with some cPanel settings, but I am very new to Java, so asking couldn't hurt...right? :D
On cPanel as I remember when you create a db user there is also a hostname associated with that user default (localhost), If you are running your code on local machine you have to add your IP (public IP) or % in hostname for this db user from cPanel. So mysql will allow connection from your machine.
Note: adding % is risky, make sure you have a strong password.

Categories

Resources