Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package DB;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.Properties;
- /**
- *
- * @author t166156
- */
- public class Database {
- /**
- * @param args the command line arguments
- */
- private static final String CREATE_TABLE_QUERY
- = " create table Currency("
- + " id int primary key,"
- + " ShortName varchar(10) not null,"
- + " FullName varchar(50) not null,"
- + " Unit varchar(50) not null,"
- + " Symbol varchar(10) not null,"
- + " \"Country\" int)";
- private static final String INSERT_DATA_QUERY
- = "insert into Currency values(?,?,?,?,?,?)";
- private static final String SELECT_DATA_QUERY
- = "select * from Currency";
- public static void main(String[] args) {
- Connection conn = null;
- try {
- conn = getConnection();
- //create table
- conn.createStatement().executeUpdate(CREATE_TABLE_QUERY);
- PreparedStatement st = conn.prepareStatement(INSERT_DATA_QUERY);
- st.setInt(1, 1);
- st.setString(2, "ad");
- st.setString(3, "kkkkkkk");
- st.setString(4, "ja");
- st.setString(5, "aa");
- st.setInt(6, 1);
- st.executeUpdate();
- st.close();
- } catch (SQLException ex) {
- System.err.println("Error1: " + ex.getMessage());
- }
- try {
- ResultSet rs = conn.createStatement().executeQuery(SELECT_DATA_QUERY);
- while (rs.next()) {
- String id = rs.getString("id");
- String shortname = rs.getString("ShortName");
- String fullname = rs.getString("FullName");
- String unit = rs.getString("Unit");
- String symbol = rs.getString("Symbol");
- String output = "\nCurrency:\n Id:%s\n shortname:%s\n fullname:%s\n Unit:%s\n Symbol:%s";
- System.out.println(String.format(output, id, shortname, fullname, unit, symbol));
- }
- rs.close();
- conn.close();
- } catch (SQLException ex) {
- System.err.println("Error2: " + ex.getMessage());
- }
- }
- public static Connection getConnection() {
- Properties props = new Properties();
- FileInputStream fis = null;
- Connection conn = null;
- try {
- fis = new FileInputStream("derbydb.properties");
- props.load(fis);
- Class.forName(props.getProperty("DATABASE_DRIVER"));
- conn = DriverManager.getConnection(props.getProperty("DATABASE_URL"),
- props.getProperty("DATABASE_USERNAME"),
- props.getProperty("DATABASE_PASSWORD"));
- } catch (IOException | ClassNotFoundException | SQLException ex) {
- System.err.println("Error: " + ex.getMessage());
- }
- return conn;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement