UNIX socket implementation for Java?

后端 未结 7 723
感动是毒
感动是毒 2020-11-27 16:10

I realize that since UNIX sockets are platform-specific, there has to be some non-Java code involved. Specifically, we\'re interested in using JDBC to connect to a MySQL in

7条回答
  •  甜味超标
    2020-11-27 16:31

    Some searching on the internet has uncovered the following useful-looking library:

    http://www.nfrese.net/software/gnu_net_local/overview.html

    Wayback Link

    Writing a socket factory should be easy enough. Once you've done so, you can pass it to your driver THUSLY.(Wayback Link).

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    import com.mysql.management.driverlaunched.ServerLauncherSocketFactory;
    
    public class ConnectorMXJTestExample {
        public static void main(String[] args) throws Exception {
            String hostColonPort = "localhost:3336";
    
            String driver = com.mysql.jdbc.Driver.class.getName();
            String url = "jdbc:mysql://" + hostColonPort + "/" + "?"
                    + "socketFactory="
                    + ServerLauncherSocketFactory.class.getName();
            String userName = "root";
            String password = "";
    
            Class.forName(driver);
            Connection conn = null;
            try {
                conn = DriverManager.getConnection(url, userName, password);
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT VERSION()");
                rs.next();
                String version = rs.getString(1);
                rs.close();
                stmt.close();
    
                System.out.println("------------------------");
                System.out.println(version);
                System.out.println("------------------------");
            } finally {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ServerLauncherSocketFactory.shutdown(hostColonPort);
            }
        }
    }
    

提交回复
热议问题