再构造一个makefile:
LIBFLAG= -lstdc++ -lpthread -ldl
CPPFLAGS = -c -fPIC -I /Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home/include -I /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers
COMMON_OBJs = com_lxjdb_jdbc_LxjDbApi.o
SHARELIB = -lLxjDbApi
libLxjDbJdbcApi: $(COMMON_OBJs)
gcc $(COMMON_OBJs) $(LIBFLAG) $(SHARELIB) -rdynamic -dynamiclib -fPIC -install_name /usr/lib/libLxjDbJdbcApi.dylib -o libLxjDbJdbcApi.dylib
make后将生成一个os x下的共享库:
libLxjDbJdbcApi.dylib注意,因为java的jni在mac下使用共享库比较特别,需要将该文件改名为libLxjDbJdbcApi.jnilib并拷贝到/usr/lib/java目录下。
第二步,实现各接口类:
1、Driver类
注意务必要重写jdbcCompliant()方法并返回false,表示我们不需要全面兼容实现所有的jdbc接口,只要实现必须的部分。
主要实现connect()方法,代码如下:
package com.lxjdb.jdbc;
import java.sql.*;
import java.util.*;
import java.util.logging.Logger;
public class Driver implements java.sql.Driver{
public LxjDbApi lxjdb;
static{
try{
java.sql.DriverManager.registerDriver(new Driver());
}
catch(SQLException e){
// System.err.println(e);
throw new RuntimeException("Can't register driver!");
}
}
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
lxjdb = new LxjDbApi();
}
public boolean acceptsURL(String url) throws SQLException{
return url.startsWith("jdbc:lxjdb://");
}
public Connection connect(String url, Properties info) throws SQLException{
if( !acceptsURL( url)){
return null;
}
// 要分解url得到主机地址和端口号,并从info得到用户名和密码
try {
String[] arr=url.split("//");
String url2 = arr[1];
String[] arr2=url2.split(":");
String host = arr2[0];
int port = Integer.parseInt(arr2[1]);
String user = info.getProperty("user");
String pwd = info.getProperty("password");
return new LxjDbConnection(lxjdb, host, port, user, pwd);
}
catch(Exception e){
throw new SQLException(e.getMessage());
}
}
public boolean jdbcCompliant(){
return false;
}
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
throws SQLException {
// TODO Auto-generated method stub
return new DriverPropertyInfo[0];
}
public int getMajorVersion() {
// TODO Auto-generated method stub
return 1;
}
public int getMinorVersion() {
// TODO Auto-generated method stub
return 0;
}
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
}
2、Connection类
主要是实现createStatement()方法:
package com.lxjdb.jdbc;
import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
public class LxjDbConnection implements java.sql.Connection{
public long conn=0;
public LxjDbApi lxjdb;
public LxjDbConnection(LxjDbApi plxjdb, String host, int port, String user, String pwd)
throws SQLException {
lxjdb = plxjdb;
conn = lxjdb.Open(host, port, user, pwd);
if(conn==0){
String info = "Open Err: "+host+":"+port+",user="+user;
throw new SQLException(info);
}
}
public Statement createStatement() throws SQLExcep