clickhouse php,java,go,python代码 实例

张映 发表于 2021-08-26

分类目录: clickhouse

标签:, , , ,

结合官方文档,做了一些实例php,java,go,python

一,phpclickhouse,非官方插件

1,安装插件

composer require smi2/phpclickhouse

2,php代码

<?php

require 'vendor/autoload.php';

$config = [
'host' => '10.0.10.23',
'port' => '8123',
'username' => 'tanktest',
'password' => '123456'
];
$db = new ClickHouseDB\Client($config);
$db->database('netjoytest1');
$statement = $db->select('SELECT * FROM tank1_all order by id desc LIMIT 1');
print_r($statement->fetchOne());

3,运行结果

zhangying test$ php ck.php
Array
(
    [id] => 6
    [name] => tank
    [age] => 0
    [create_time] => 2021-08-23 14:21:30
)

二,clickhouse-jdbc,clickhouse官方库

1,修改pom.xml

<dependency>
    <groupId>ru.yandex.clickhouse</groupId>
    <artifactId>clickhouse-jdbc</artifactId>
    <version>0.3.1</version>
</dependency>

测试代码用的框架是springboot

2,java测试代码

package tank.test.springboot;

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

public class ck {
    private static Connection connection = null;

    public static void main(String[] args) throws SQLException {

        try {
            Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
            String url = "jdbc:clickhouse://10.0.10.23:8123/netjoytest1";
            String user = "tanktest";
            String password = "123456";
            connection = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from tank1_all limit 1");
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (resultSet.next()) {
            for (int i = 1; i <= columnCount; i++) {
                System.out.println(metaData.getColumnName(i) + ":" + resultSet.getString(i));
            }
        }
    }
}

3,运行结果

=========省略============
16:54:28.570 [main] DEBUG org.apache.http.headers - http-outgoing-0 << X-ClickHouse-Summary: {"read_rows":"0","read_bytes":"0","written_rows":"0","written_bytes":"0","total_rows_to_read":"0"}
16:54:28.570 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Connection can be kept alive for 300000 MILLISECONDS
16:54:28.571 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection [id: 0][route: {}->http://10.0.10.23:8123] can be kept alive for 300.0 seconds
16:54:28.571 [main] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-0: set socket timeout to 0
16:54:28.571 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {}->http://10.0.10.23:8123][total kept alive: 1; route allocated: 1 of 500; total allocated: 1 of 10000]
id:2
name:tank
age:0
create_time:2021-08-23 14:21:30
断开与目标 VM 的连接,地址:'127.0.0.1:60371', transport: 'socket'

进程已结束,退出代码 0

三,clickhouse-driver  非clickhouse官方库

1,安装clickhouse-driver

pip install clickhouse-driver

2,python测试代码

#!/usr/bin/env python

from clickhouse_driver import Client
client = Client(host='10.0.10.23', database='netjoytest1', user='tanktest', password='123456')
a = client.execute('select * from tank1_all limit 1')
print(a)

3,运行结果

/usr/local/bin/python2.7 /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 61549 --file /Users/zhangying/PycharmProjects/test/ck.py
pydev debugger: process 34569 is connecting

Connected to pydev debugger (build 192.7142.42)
[(2, u'tank', 0, datetime.datetime(2021, 8, 23, 14, 21, 30))]

进程已结束,退出代码 0

四,clickhouse-go clickhouse官方库

1,安装clickhouse-go

go get -u github.com/ClickHouse/clickhouse-go  //官方库
go get -u github.com/jmoiron/sqlx   //装这个是为了下面运行代码用

2,go代码

package main

import (
	_ "github.com/ClickHouse/clickhouse-go"
	"github.com/jmoiron/sqlx"
	"log"
)

func main() {

	var tcpinfo = "tcp://10.0.10.23:9000?username=tanktest&password=123456&database=netjoytest1&read_timeout=10&write_timeout=20&alt_hosts=10.0.10.24:9000"

	connect, err := sqlx.Open("clickhouse", tcpinfo)
	if err != nil {
		log.Fatal(err)
	}
	var items []struct {
		Id   uint8     `db:"id"`
		Name string    `db:"name"`
		Age   uint8     `db:"age"`
		Create_time  string `db:"create_time"`
	}

	if err := connect.Select(&items, "select * from tank1_all order by id desc limit 2"); err != nil {
		log.Fatal(err)
	}

	for _, item := range items {
		log.Printf("id: %d, name: %s, age: %d, create_time: %s", item.Id, item.Name, item.Age, item.Create_time)
	}
}

注意这里的端口是9000,不是8123

3,运行结果

GOROOT=/usr/local/Cellar/go/1.14/libexec #gosetup
GOPATH=/Users/zhangying/go #gosetup
/usr/local/Cellar/go/1.14/libexec/bin/go build -o /private/var/folders/xf/v0p6y_p961z0k86r6n0fm5x00000gn/T/___go_build_awesomeProject awesomeProject #gosetup
/private/var/folders/xf/v0p6y_p961z0k86r6n0fm5x00000gn/T/___go_build_awesomeProject #gosetup
2021/08/25 18:18:09 id: 6, name: tank, age: 0, create_time: 2021-08-23T14:21:30+08:00
2021/08/25 18:18:09 id: 5, name: tank, age: 0, create_time: 2021-08-23T14:21:30+08:00

Process finished with exit code 0

注意,除了php外,其他的代码都是在ide中调试执行



转载请注明
作者:海底苍鹰
地址:http://blog.51yip.com/clickhouse/2527.html

留下评论

留下评论
  • (必需)
  • (必需) (will not be published)
  • (必需)   2X3=?