Create a gist now

Instantly share code, notes, and snippets.

@scmy /DbInsert.java
Last active Feb 11, 2016

What would you like to do?
PROG2 - IO - JDBC: diverses Kleinzeugs

H2 Datenbank-Kleinzeug

Diverses Kleinzeugs, inkl die Sache mit den generated Keys in DbInsert.java

Tipp: an Einfachsten bearbeiten Sie die Datenbank mit einem "Service" von Netbeans oder mit SQuirreL SQL

drop all objects;
CREATE TABLE towns(id int auto_increment primary key , name varchar, kanton varchar);
insert into towns values (1, 'Winterthur', 'ZH');
insert into towns values (2, 'St. Gallen', 'SG');
insert into towns values (3, 'Neuchâtel', 'NE');
import java.sql.*;
public class DbInsert {
public static final String DB_CONN = "jdbc:h2:~/datenbanken/H2/prog2townst;AUTO_SERVER=TRUE";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection(DB_CONN);
String sql = "insert into towns(name, kanton) values (?, ?); ";
PreparedStatement st = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
st.setString(1, "Brig");
st.setString(2, "VS");
st.executeUpdate();
ResultSet generatedKeys = st.getGeneratedKeys();
generatedKeys.next();
int key = generatedKeys.getInt(1);
System.out.printf("Neue Stadt hat Index %1$s bekommen \n", key);
con.close();
}
}
import java.sql.*;
public class DbLoader {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection(DbTest.DB_CONN );
Statement st = con.createStatement();
st.execute("runscript from 'datenbank.sql'");
con.close();
}
}
Sign in to join this conversation on GitHub.