VastbaseG100

基于openGauss内核开发的企业级关系型数据库。

Menu

无框架配置

下载Druid的jar包,除Vastbase G100 JDBC驱动外,引入pom依赖如下:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>

在resource目录下配置db_server.properties文件

driverClassName=org.postgresql.Driver
url=jdbc:postgresql://127.0.0.1:5432/test
username=root
password=123456
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200;

Java代码

// DBPoolConnection类
import com.alibaba.druid.pool.*;
import org.apache.log4j.*;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.util.Properties;

public class DBPoolConnection {
	static Logger log = LogManager.getLogger(DBPoolConnection.class);
	private static DBPoolConnection dbPoolConnection = null;
	private static DruidDataSource druidDataSource = null;

	static {
		Properties properties = new Properties();
		try {
			properties.load(new FileInputStream(ClassLoader.getSystemResource("db_server.properties").getPath()));
			druidDataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties); //DruidDataSrouce工厂模式
		} catch (Exception e) {
			log.error("获取配置失败");
		}
	}

	/**
	* 数据库连接池单例
	* @return
	*/
	public static synchronized DBPoolConnection getInstance(){
		if (null == dbPoolConnection){
			dbPoolConnection = new DBPoolConnection();
		}
		return dbPoolConnection;
	}

	/**
	* 返回druid数据库连接
	* @return
	* @throws SQLException
	*/
	public DruidPooledConnection getConnection() throws SQLException{
		return druidDataSource.getConnection();
	}
}

在Vastbase G100创建表student:

create table student(id int,name varchar(20),num int,score numeric(4,2));

运行以下代码连接Vastbase G100并写入一条数据到表student。

import com.alibaba.druid.pool.DruidPooledConnection;
import java.sql.*;

public class TestDruid{
    public static void main(String[] args) throws SQLException {
        DruidPooledConnection dsConn = DBPoolConnection.getInstance().getConnection();
        Connection conn = dsConn.getConnection();

        //execute SQL
        String sql = "INSERT INTO student VALUES (NULL, ?, ?, ?);";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, "sam");
        pstmt.setInt(2, 35);
        pstmt.setDouble(3, 88.5);
        int i = pstmt.executeUpdate();
        System.out.println("insert rows: " + i);
        
        pstmt.close();
        //release connection and give back to pool
        conn.close();
    }
}