Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC MySQL connection using Unix Socket

I am using MySQL using the --skip-networking option on Linux.

Trying to connect my J2EE based application (using servlets) to the MySQL database using JDBC.

When was using MySQL with the --skip-networking option disabled, I was connecting to the database as:

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","myuser","mypassword");

After having enabled the --skip-networking option, I am trying to connect it as:

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase","myuser","mypassword");

But this does not seem to work, and I get java.lang.NullPointerException when I try to connect to the database in my application.

After commenting out the --skip-networking option and using the old JDBC statement, I can connect to the database.

Note - I am able to connect to the database via the command line mysql client with the --skip-networking option enabled.

Can anyone tell me how to connect to the database from JDBC? I tried searching for it but could not any satisfactory answer that worked. Thanks in advance.

like image 679
abchk1234 Avatar asked Sep 18 '14 17:09

abchk1234


People also ask

Is it possible to connect to MySQL via Unix socket from another host?

"Unix sockets" are not TCP/IP sockets. They are always limited to the current system only – it is not possible to connect to another system's socket over the network. Because of that, the hostname localhost is special in MySQL and the client doesn't actually attempt to look up its IP address at all.

How do I use a domain socket in Unix?

To create a UNIX domain socket, use the socket function and specify AF_UNIX as the domain for the socket. The z/TPF system supports a maximum number of 16,383 active UNIX domain sockets at any time. After a UNIX domain socket is created, you must bind the socket to a unique file path by using the bind function.

How do I find MySQL socket path?

The default location for the Unix socket file that the server uses for communication with local clients is /var/lib/mysql/mysql.


1 Answers

The JDBC Driver from the MariaDB project supports Unix domain sockets while remaining compatible with the MySQL Connector/J JDBC driver. Example jdbc url for the MariaDB driver is: jdbc:mariadb://localhost:3306/revmgt?localSocket=/var/run/mysqld/mysqld.sock

Worth noting that this requires including the JNA library as the MariaDB driver uses domain sockets via JNA internally. I saw speed improvements for CPU bound java processes when using the unix domain sockets. I believe this was largely from the offload of work from the java process to native code freeing up CPU cycles for the already CPU bottle necked java process.

like image 121
Robert Avatar answered Oct 04 '22 00:10

Robert