今天学习了下vert.x的JDBCClient,我这里将今天的学习笔记记录下来。这次学习中使用了c3p0。
用使用JDBCClient和c3p0得现在pom.xml文件里面导入对应的依赖,下面贴出xml文件中的内容:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javafm</groupId> <artifactId>vertx.vertxworld</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-core</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-web</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-web-templ-thymeleaf</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-jdbc-client</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
配置好依赖后,就可以编写我们的代码了,创建一个DataAccess.java文件,写入代码
package com.javafm.vertx.helloworld; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.ext.jdbc.JDBCClient; /** * Created by lemontea <36634584@qq.com> on 16-12-23. */ public class DataAccess { private static DataAccess dataAccess; private static JDBCClient jdbcClient; private static JsonObject config; static { config = new JsonObject(); config.put("url", "jdbc:mysql://localhost:3306/test"); config.put("driver_class", "com.mysql.jdbc.Driver"); config.put("user", "root"); config.put("password", "password"); } public static DataAccess create(Vertx vertx) { if (dataAccess == null) { synchronized (DataAccess.class) { if (dataAccess == null) { dataAccess = new DataAccess(); dataAccess.init(vertx); } } } return dataAccess; } private void init(Vertx vertx) { jdbcClient = JDBCClient.createShared(vertx, config); } public JDBCClient getJDBCClient() { return jdbcClient; } }
编写测试代码,查询test表,并输入索引 0、1位置的数据:
public static void main(String[] args) { Vertx vertx = Vertx.vertx(); DataAccess dataAccess = DataAccess.create(vertx); dataAccess.getJDBCClient().getConnection(res -> { if (res.succeeded()) { SQLConnection conn = res.result(); conn.query("SELECT * FROM `test`", res2 -> { ResultSet rs = res2.result(); rs.getResults().forEach(e -> { System.out.println(e.getInteger(0) + " " + e.getString(1)); }); conn.close(); }); } else { System.out.println(res.cause()); } }); }
运行这个main方法,会在idea控制台输出结果:
原创文章,转载请注明出处。