Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package koti3;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import com.mysql.jdbc.PreparedStatement;
- public class DBConnect {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- System.out.println("Valitse 1) Lisää 2) Poista 3) Muuta 4) Päivitä Lista");
- Scanner scanner = new Scanner(System.in);
- int command = scanner.nextInt();
- System.out.println(command);
- //Here switch/case depending what command
- //
- }
- String kysely = "SELECT asiakasID, asiakas, osoite, postinumero,toimipaikka, sahkoposti FROM asiakas1";
- try {
- // ladataan ajuri
- Class.forName("com.mysql.jdbc.Driver");
- } catch (Exception e) {
- System.out.println("Virhe tietokanta-ajuria ladattaessa " + e);
- System.exit(1); // lopetetaan ohjelma tähän
- }
- //Tietokantayhteys Connection
- try (Connection con = DriverManager.getConnection(
- "jdbc:mysql://mysql.cc.puv.fi:3306/e1400519_java", "e1400519",
- "d9j3GZJpcPWv")) {
- //Statement SQL-lauseita ja ResultSet tulosjoukkoa varten
- try (Statement stm = con.createStatement();
- ResultSet rs = stm.executeQuery(kysely)) {
- System.out.println("ASIAKASTIEDOT\n"); // tulostetaan näyttölle
- //Käydään tulosjoukko ResultSet läpi
- while (rs.next()) {
- String asiakasID = rs.getString(1); // tai rs.getString("asiakasID");
- String asiakas = rs.getString(2);
- String osoite = rs.getString(3);
- String postinumero = rs.getString(4);
- String toimipaikka = rs.getString(5);
- String sahkoposti = rs.getString(6);
- System.out.println(asiakasID + ": " + asiakas + ", "
- + osoite + ", " + postinumero
- + ", " + toimipaikka
- + ", " + sahkoposti + " ");
- }
- } //try with Statement ja ResultSet päättyy
- } //try with Connection päättyy
- catch (SQLException e) {
- System.out.println("Ongelmia tietokannan kasittelyssa "
- + e.getMessage());
- }
- }
- }
- public void insert(Connection con, String asiakasID, String asiakas, String osoite, String postinumero, String toimipaikka, String sahkoposti) throws SQLException {
- //Tietokantayhteys Connection
- try (PreparedStatement ps = (PreparedStatement) con.prepareStatement(
- "INSERT INTO asiakas(asiakasID, asiakas, osoite, postinumero, toimipaikka, sahkoposti) VALUES(?, ?, ?, ?, ?, ?, ?)")){
- //ps = con.prepareStatement("Lisää uudet asiakastiedot, asiakasID, asiakas, osoite, postinumero, toimipaikka, sahkoposti,");
- ps.setString(1, asiakasID);
- ps.setString(2, asiakas);
- ps.setString(3, osoite);
- ps.setString(4, postinumero);
- ps.setString(5, toimipaikka);
- ps.setString(6, sahkoposti);
- int i = ps.executeUpdate();
- if (i != 0) {
- System.out.println("Inserted");
- } else {
- System.out.println("not Inserted");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement