Sample database connection - WePaHT-SQL/SQLTasker GitHub Wiki

Pom.xml:

4.0.0 wepaht DatabaseTest 1.0-SNAPSHOT jar
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.7.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
</dependencies>

Testiluokka:

package wepaht.db;

import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication public class Main {

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

// ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args);

    Connection helloConnection = createConnectionToDatabase("hello");
    Connection worldConnection = createConnectionToDatabase("world");

    System.out.println("Tables in hello");
    showTables(helloConnection);
    helloConnection.close();

    System.out.println("");
    System.out.println("Tables in world");
    showTables(worldConnection);

// List connections = new ArrayList<>(); //
// while(true) { // connections.add(createConnectionToDatabase(UUID.randomUUID().toString())); // } }

private static void showTables(Connection conn) throws Exception {
    DatabaseMetaData md = conn.getMetaData();
    ResultSet rs = md.getTables(null, null, "%", null);
    while (rs.next()) {
        System.out.println(rs.getString(3));
    }

    Statement stmt = conn.createStatement();

    int result = stmt.executeUpdate("CREATE TABLE Foo(id integer)");
    System.out.println("Tietokantataulu luotu");
    stmt.executeUpdate("INSERT INTO Foo (id) VALUES (3);");
    System.out.println("dataa syötetty");

    System.out.println("Tässä tulokset:");
    rs = stmt.executeQuery("SELECT * FROM Foo");
    while (rs.next()) {
        System.out.println(rs.getInt("id"));
    }

    System.out.println("");

}

private static Connection createConnectionToDatabase(String databasename) throws Exception {
    Class.forName("org.h2.Driver");
    String url = "jdbc:h2:mem:" + databasename;
    String user = "sa";
    String pwds = "sa";

    Connection conn = DriverManager.
            getConnection(url, user, pwds);

    return conn;
}

}

⚠️ **GitHub.com Fallback** ⚠️