Derby是个java数据库。
第一次接触,用了下druid的连接池。
还是maven下的,下面上代码:
pom:
<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>DerbyTest</groupId> <artifactId>DerbyTest</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>DerbyTest</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <version>10.10.2.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.7</version> </dependency> </dependencies> </project>
DruidTest.java:
package DerbyTest.DerbyTest; import java.sql.Connection; import java.sql.SQLException; import com.alibaba.druid.pool.DruidDataSource; public class DruidTest { private static DruidDataSource druidDataSource=new DruidDataSource(); static{ druidDataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); druidDataSource.setUrl("jdbc:derby:S:\\derbyTest;create=true"); //druidDataSource.setValidationQuery("select 1 from test "); druidDataSource.setTestWhileIdle(false); try { druidDataSource.init(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConn(){ try { return druidDataSource.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } }
主类的:
package DerbyTest.DerbyTest; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Set; import java.util.UUID; /** * Hello world! * */ public class App { public static void main(String[] args) throws SQLException { Connection conn = DruidTest.getConn(); PreparedStatement ps; try { ps = conn.prepareStatement("create table one(id varchar(255) primary key, str varchar(20)) "); ps.execute(); } catch (Exception e) { // e.printStackTrace(); } ps = conn.prepareStatement("insert into one(id,str) values(?,‘hi‘) "); UUID uuid = UUID.randomUUID(); ps.setString(1, "x" + uuid); ps.executeUpdate(); ps = conn.prepareStatement("select * from one "); ps.execute(); ResultSet result = ps.executeQuery(); while (result.next()) { System.out.print(result.getString(1) + "---"); System.out.println(result.getString(2)); } System.out.println("Hello World!"); } }
时间: 2024-10-17 03:35:17