Fail to connect to mysql database using Java - java

I got an exception connecting to MySQL through Java. I downloaded the MySQL Java connector and added it to the classpath. I'm trying to connect to a MySQL table without success.
I have also tried to telnet localhost 3306 but got the following error: "nodename nor servname provided, or not known"
The code is as follows:
//import java.sql.Connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class ConnectToDatabase {
public static void main(String[] args) throws Exception{
//Accessing driver from the JAR file
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/cldatabase", "root", "root");
//Here we create our query
PreparedStatement statement = con.prepareStatement(
"SELECT * FROM profiles");
ResultSet result = statement.executeQuery();
while(result.next()){
System.out.println(result.getString("firstName") + " " +
result.getString("lastName"));
}
}
And this exception was thrown:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.
CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.
I have xampp installed on my mac.
this is what comes up when I run "ps -ef | grep mysql"
0 1694 1 0 0:00.02 ?? 0:00.03 /bin/sh /Applications/XAMPP/xamppfiles/bin/mysqld_safe --datadir=/Applications/XAMPP/xamppfiles/var/mysql --pid-file=/Applications/XAMPP/xamppfiles/var/mysql/T-s-sMacBook-Air.local.pid
-2 1792 1694 0 0:00.07 ?? 0:00.28 /Applications/XAMPP/xamppfiles/sbin/mysqld --basedir=/Applications/XAMPP/xamppfiles --datadir=/Applications/XAMPP/xamppfiles/var/mysql --user=nobody --log-error=/Applications/XAMPP/xamppfiles/var/mysql/k-Air.local.err --pid-file=/Applications/XAMPP/xamppfiles/var/mysql/-MacBook-Air.local.pid --socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock --port=3306
501 1814 1484 0 0:00.00 ttys000 0:00.00 grep mysql

Do any of the answers to this similar question on ServerFault help?
1) Verify the address mysql is bound
to, it's probably 127.0.0.1 (only)
which I believe is the default (at
least on standard Ubuntu server).
You'll have to comment out the
bind-address parameter in my.cnf to
bind to all available addresses (you
can't choose multiple, it's one or
all).
2) If it is bound to 127.0.0.1 and you
can't connect using "localhost", make
sure it's not resolving to the IPv6
localhost address instead of IPv4. (or
just use the IP address)
3) Double and triple-check the port
that mysql is listening on.
4) Make sure you're using the right
JDBC connector for your JDK.
5) Make sure you're not doing
something really silly like starting
mysql with --skip-networking.
What do you get when you run "lsof -i :3306" ?

if you are facing problem on Class.forName("com.mysql.jdbc.Driver"); then copy mysql connector on following location..definately it will work..C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\lib\WEB-INF..note that in webapps folder there is no directory called lib then manually create lib and WEB-INF directory and paste mysql connector in that.no need any classpath settings.....
if still you face problem then send your query...

Related

Cannot find mysql.sock file and cannot check if mysql is running on mac using xampp

I am extremely new to Computer Science, and we were asked by our professor to connect our java file to our MySQL database using XAMPP. My java file would not connect to the database I created on phpmyadmin no matter what I did, so I tried to get to the root of the problem by entering mysqladmin -u root -p ping on my terminal. This was the result:
error: 'Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)'
Check that mysqld is running and that the socket: '/tmp/mysql.sock' exists!
I went to my tmp folder and could not find the mysql.sock file. I tried checking if mysql was running by entering ps aux | grep mysql on my terminal. The result was
username 5078 0.0 0.0 4277504 672 s001 S+ 11:21AM 0:00.00 grep mysql
but I have no idea what that means. I also tried commands like service mysql restart and sudo service mysqld start, but terminal would say
zsh: command not found: service
I tried locating for the mysql.sock file because I thought it was just misplaced, so I entered locate mysql.sock and netstat -ln | grep mysql on the terminal, but they returned nothing. I also tried mysqladmin -p -u <user-name> variables but the result again was
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)'
Check that mysqld is running and that the socket: '/tmp/mysql.sock' exists!
The weird thing is that on the Log tab of XAMPP, it says INFO: Successfully started "mysql". I am also able to connect to my databases using my php projects, but I just can't connect with my java files. Please help, I am desperate.

Connect Hbase Stand Alone in Virtualbox VM from Windows 10 with Java application

i´m trying to connect (and create new table) to HBase intalled in a Ubuntu VM using a Java app running in Windows 10.
I´m sure that HBase is working and java code too because if i send it directly in the Intellij installed inside VM it´s works, but if i launch java app in Windows (host maquine) returns this error:
"Exception in thread "main" org.apache.hadoop.hbase.client.RetriesExhaustedException: Failed after attempts=5, exceptions:
2020-02-17T15:38:25.890Z, RpcRetryingCaller{globalStartTime=1581953902178, pause=100, maxAttempts=5}, org.apache.hadoop.hbase.MasterNotRunningException: java.net.ConnectException: Call to danny-VirtualBox/192.168.56.101:16000 failed on connection exception: org.apache.hbase.thirdparty.io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: danny-VirtualBox/192.168.56.101:16000"
I have this code:
public static void main(String[] args) throws Exception {
Configuration con = HBaseConfiguration.create();
con.clear();
con.set("hbase.zookeeper.quorum", "192.168.56.101");
con.set("hbase.master", "192.168.56.101:16000");
con.set("hbase.zookeeper.property.clientport", "2181");
con.set("hbase.client.retries.number", "4");
con.set("hbase.rpc.timeout", "3000");
con.set("hbase.security.authentication", "simple");
con.set("zookeeper.znode.parent", "/hbase");
Connection conn = ConnectionFactory.createConnection(con);
Admin admin = conn.getAdmin();
// Instantiating table descriptor class
HTableDescriptor tableDescriptor = new
HTableDescriptor(TableName.valueOf("emp2"));
// Adding column families to table descriptor
tableDescriptor.addFamily(new HColumnDescriptor("personal"));
tableDescriptor.addFamily(new HColumnDescriptor("professional"));
// Execute the table through admin
admin.createTable(tableDescriptor);
System.out.println(" Table created ");}
I´m sure that Host can "see" VM because i can open HBase Web panel in Windows
(http://192.168.56.101:16010/master-status)
So, i think problem is ports or something about net security but i could not resolve the issues. Colud you help me?
IP windows machine: 192.168.56.1
IP VM: 192.168.56.101
I have modify host file in vm (hbase machine) with this values:
Finally i resolved the issue, you have to edit hosts file in HBase server to change the line:
127.0.0.1 localhost
for
192.168.56.101 nameServer

Derby db connectivity problems

I receive the following error msg when attempting to connect to a derby network server:
java.sql.SQLException: No suitable driver found for jdbc:derby://localhost/studentdb;create=true
Derby is properly installed and all environment variables set. I am able to start the derby NetworkServerControl from a Windows command prompt with the following command:
java org.apache.derby.drda.NetworkServerControl start -h localhost
,and I can do this from any location within my system's directory tree.
I can start the derby ij client from within a Windows command prompt with the command:
java org.apache.derby.tools.ij
,again, from any location within my system's directory tree.
But the code snippet below is unable to make this connection:
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:derby://localhost/studentdb;create=true";
//the error happens here, the program executes no further
conn = DriverManager.getConnection(url,null);
Statement stmt = conn.createStatement();
}
Placing the port value in the url string makes no difference.
Any suggestions would be much appreciated.
You must add the derby jdbc driver to your classpath (from derbyclient.jar, since this is the ClientDriver), then use this instruction to load the driver :
Class.forName("org.apache.derby.jdbc.ClientDriver");
So I encountered this error and it was quite an irritating and hectic task to resolve this. But in the end, I managed to find a perfect video that made me install derby from the start and guided me perfectly on how to install it. However, there is one more step after the video.
Watch this video if you have set up JavaFX packages and are able to run the program normally, but facing
"java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/DBNAME;create=true" issue when trying to run with the database.
Link to the tutorial -> https://www.youtube.com/watch?v=OKiBsWbgrMw
Now after this is set up you will now be able to start/stop the database (via the services tab) and will be able to connect with the DB. But the issue will still persist in trying to edit the DB.
To rectify this, follow the steps ->
Right click on project ---> Properties ---> Libraries ---> Click on '+' in Classpath ---> Add jar/folder ---> Go to the lib folder inside the derby and select derbyclient.jar
VERSIONS
JAVA - 17.0.1, Netbeans - 12.6

No suitable driver when trying to create SQL database [duplicate]

This question already has answers here:
SQLException: No suitable driver found for jdbc:derby://localhost:1527
(19 answers)
Closed 7 years ago.
I am trying to create a new SQL database with this Java program
import java.sql.*; //Needed for JDBC classes
public class BuildPhonebookDB {
public static void main(String[] args) throws Exception{
//Create a named constant for the URL
final String DB_URL = "jdbc:derby:Phonebook;create=true";
try {
//Create a connection to the database.
Connection conn = DriverManager.getConnection(DB_URL);
//Create a Statement object.
Statement stmt = conn.createStatement();
//Create the Entries table
stmt.execute("CREATE TABLE Entries (" +
"Name CHAR(20)"+
"Number INTEGER)"
);
System.out.println("Database Connected");
//Close the connection
conn.close();
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
When I try to run the program I get an error that:
No suitable driver found for jdbc:derby:Phonebook;create=true
I have looked at various other similar posts on Stack Overflow, such as this one, but none help. I have seen things about a driver jar, but I don't know what this is, if I need to edit this, could someone help me through it?
Thanks for any help
Did you see this guide and have you complited all step of this guide?
Apache Derby
Download Derby Download the binary Apache Derby distribution from the
Derby web site at http://db.apache.org/derby/derby_downloads.html.
These tutorial instructions use version 10.12.1.1 and assume you
downloaded one of the binary distribution files listed in the table
below:
Operating System Download File Windows db-derby-10.12.1.1-bin.zip
UNIX, Linux, and Mac db-derby-10.12.1.1-bin.tar.gz If a more recent
release is available, download that, then substitute that version
number for 10.12.1.1 in the following instructions.
Install Derby Choose the directory into which you want to install the
Derby software. You must have write permissions to this directory. The
sample instructions below use C:\Apache for Windows and /opt/Apache
for UNIX; be sure to use your actual location. Copy the software
distribution to the location you choose, then extract it as shown
below.
Windows (use your extraction tool e.g. WinZip -- these instructions
use mks unzip):
mkdir C:\Apache copy db-derby-10.12.1.1-bin.zip
> C:\Apache cd C:\Apache unzip db-derby-10.12.1.1-bin.zip
UNIX:
mkdir /opt/Apache cp db-derby-10.12.1.1-bin.tar.gz /opt/Apache
> cd /opt/Apache tar xzvf db-derby-10.12.1.1-bin.tar.gz
In both cases, the software will now be extracted into a subdirectory
named db-derby-10.12.1.1-bin.
Set DERBY_INSTALL Set the DERBY_INSTALL variable to the location where
you installed Derby. Examples are shown below, but be sure to use the
actual location on your system:
Windows: C:\> set DERBY_INSTALL=C:\Apache\db-derby-10.12.1.1-bin
UNIX Korn Shell:
$ export
> DERBY_INSTALL=/opt/Apache/db-derby-10.12.1.1-bin
Configure Embedded Derby To use Derby in its embedded mode set your
CLASSPATH to include the jar files listed below:
derby.jar: contains the Derby engine and the Derby Embedded JDBC
driver derbytools.jar: optional, provides the ij tool that is used by
a couple of sections in this tutorial You can set your CLASSPATH
explicitly with the command shown below:
Windows:
C:\> set
> CLASSPATH=%DERBY_INSTALL%\lib\derby.jar;%DERBY_INSTALL%\lib\derbytools.jar
;.
UNIX:
$ export
> CLASSPATH=$DERBY_INSTALL/lib/derby.jar:$DERBY_INSTALL/lib/derbytools.jar:.
...
Step 3: Embedded Derby
When an application accesses a Derby database using the Embedded Derby
JDBC driver, the Derby engine does not run in a separate process, and
there are no separate database processes to start up and shut down.
Instead, the Derby database engine runs inside the same Java Virtual
Machine (JVM) as the application. So, Derby becomes part of the
application just like any other jar file that the application uses.
Figure 1 depicts this embedded architecture.
Set the environment
To set up the environment, follow the "Configure Embedded Derby"
instructions.
Use this before you get the connection from the driver:
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();

How can I start apache derby programmatically jar file?

I have a Java application, which uses Apache Derby. Using Eclipse Export option, I exported it as JAR file. When I am running Eclipse, and the server is connected to port 1527, the JAR executes correctly.
However when eclipse is closed, (and the server is not connected to 1527) on executing jar, i get this error
java.sql.SQLNonTransientConnectionException: java.net.ConnectException
: Error connecting to server localhost on port 1527 with message
Connection refused.
This is understandable. But i want to distribute the JAR. So is there a way to start the server programmatically, whenever JAR is executed?
You can start the NetworkServer programmatically:
NetworkServerControl serverControl = new NetworkServerControl(InetAddress.getByName("myhost"),1621)
serverControl.shutdown();
Simplest is to use embedded Derby
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
conn = DriverManager.getConnection("jdbc:derby:" + DATA_STORE + ";create=true");
You need to start the server programmatically.
How this is done is documented in the manual:
http://db.apache.org/derby/docs/10.8/adminguide/tadminconfig814963.html

Categories

Resources