Java连接Neo4j

一、使用jdbc连接

      使用jdbc连接没有大变化,使用的时候和mysql过程比较类似,除了Cypher


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class JDBCConnection {
	public static void jdbcNeo4j() throws ClassNotFoundException, SQLException{
		Class.forName("org.neo4j.jdbc.Driver");
		String url ="jdbc:neo4j:http://localhost:7474";
		Connection conn = DriverManager.getConnection(url, "neo4j_user", "neo4j_passwd");
		
		Statement stmt = conn.createStatement();
		/*ResultSet rs = stmt.executeQuery("match (n) return n.age,n.name,n");
		while(rs.next()) {
			System.out.println(rs.getString("n.name")+"\t"+rs.getString("n.age"));
			System.out.println("rs.getString(\"n\")\t"+rs.getString("n"));
			System.out.println("rs.getString(2)\t"+rs.getString(2));
			System.out.println("rs.getString(3)\t"+rs.getString(3));
		}*/
		ResultSet rs = stmt.executeQuery("match (n) return n limit 10");
		while(rs.next()) {
			System.out.println(rs.getRow());
			System.out.println(rs.getMetaData().getColumnName(0));
		}
	}
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		jdbcNeo4j();
	}
}

二、使用GraphDatabase连接

其中用到的Values.parameters(),可以先生成一个数组(一般为Object[]类型),其中奇数项为参数名,偶数项为参数值,返回值为Value类型,以下是源码:

    public static Value parameters( Object... keysAndValues )//不定长参数的传递通过数组实现
    {
        if ( keysAndValues.length % 2 != 0 )
        {
            throw new ClientException( "Parameters function requires an even number " +
                                       "of arguments, " +
                                       "alternating key and value. Arguments were: " +
                                       Arrays.toString( keysAndValues ) + "." );
        }
        HashMap map = newHashMapWithSize( keysAndValues.length / 2 );
        for ( int i = 0; i < keysAndValues.length; i += 2 )
        {
            Object value = keysAndValues[i + 1];
            assertParameter( value );
            map.put( keysAndValues[i].toString(), value( value ) );
        }
        return value( map );
    }

即可有类似如下写法:

String message = "message";
String message2= "message2";
Object[] obj= new Object[] {"message", message,"message2",message2};
Value v =Values.parameters( obj );//传入到parameters方法中的是数组
StatementResult result = tx.run( "CREATE (a:Greeting) " +
	      "SET a.message = $message,a.message2=$message2 " +
	      "RETURN a.message + ', from node ' + id(a)", v );


以下是官网扒的demo稍作修改:

import java.util.List;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import org.neo4j.driver.v1.Values;
import org.neo4j.driver.v1.Driver;

public class GraphDatabaseConnection implements AutoCloseable {
	private final Driver driver;
	
	public GraphDatabaseConnection() {
		//default port is 7687
		String uri="bolt://localhost:7687";
		driver = GraphDatabase.driver(uri,AuthTokens.basic(username,password));
	}
	public void close() {
		 driver.close();
	}
	 public void printGreeting( final String message )
	    {
	        try ( Session session = driver.session() )
	        {
	            String greeting = session.writeTransaction( new TransactionWork()
	            {
	                @Override
	                public String execute( Transaction tx )
	                {
	                	String statementTemplate="MATCH (n) RETURN n.name,n.age,n LIMIT 25";
	                    /*StatementResult result = tx.run( "CREATE (a:Greeting) " +
	                                                     "SET a.message = $message " +
	                                                     "RETURN a.message + ', from node ' + id(a)",
	                                                     Values.parameters( "message", message ) );
	                    return result.single().get( 0 ).asString();*/
	                	StatementResult result = tx.run(statementTemplate);
	                	List resultList = result.list();
	                	String resultString="";
	                	for (Record record : resultList) {
	                		System.out.println(record.get("n.name")+"\t"+record.get("n.age"));
	                		System.out.println(record.get("n").get("name")+"\t"+record.get("n").get("age"));
	                		resultString=resultString+"\n\t"+record.get(0).toString()+record.get(1).toString();
						}	                	
						return resultString;                	
	                }
	            } );
	            System.out.println( greeting );
	        }
	    }
	 
	 public static void main( String... args ) throws Exception
	    {
	        try ( GraphDatabaseConnection greeter = new GraphDatabaseConnection() )
	        {
	            greeter.printGreeting( "hello, world" );
	        }
	    }
}

    关于GraphDatabase连接方式,其实官网有demo点击打开链接,官方使用的是静态导入,如果不使用静态导入,需要将Values.parameters写成parameters,否则会不能使用。

先导入neo4j-jdbc-driver-x.x.x.jar驱动包到项目,同时注意后续类都使用这个包里面的类(即org.neo4j.driver开头的类) 

注释掉的部分是 官网demo点击打开链接的部分内容。

你可能感兴趣的:(数据库,Neo4j,neo4j,java,jdbc,GraphDatabase,数据库)