Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package toka;
- import java.sql.*;
- import java.util.Scanner;
- public class Test {
- static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
- //static final String DB_URL = "jdbc:mariadb://localhost/db20";
- static final String DB_URL = "jdbc:mysql://localhost/db20?";
- // Database credentials
- static final String USER = "mikko20";
- static final String PASS = "kt123456";
- public static void main(String[] args) {
- Connection conn = null;
- Statement stmt = null;
- try {
- //STEP 2: Register JDBC driver
- Class.forName(JDBC_DRIVER);
- System.out.println("Connecting to a selected database...");
- /*conn = DriverManager.getConnection(
- DB_URL, USER, PASS);*/
- conn = DriverManager.getConnection(
- DB_URL + "user=" + USER + "&password=" + PASS);
- System.out.println("Connected database successfully...");
- stmt = conn.createStatement();
- Scanner scan = new Scanner(System.in);
- int idr = 0;
- System.out.println("Anna id");
- idr = scan.nextInt();
- String etunimi;
- System.out.println("Anna etunimi: ");
- etunimi = scan.next();
- String sukunimi;
- System.out.println("Anna sukunimi: ");
- sukunimi = scan.next();
- System.out.println("Anna ikä");
- int ika = scan.nextInt();
- String sqlInsert = "INSERT INTO REGISTRATION VALUES(";
- sqlInsert += String.valueOf(idr);
- sqlInsert += ",'";
- sqlInsert += etunimi;
- sqlInsert += "','";
- sqlInsert += sukunimi;
- sqlInsert += "',";
- sqlInsert += String.valueOf(ika);
- sqlInsert += ")";
- stmt.executeUpdate(sqlInsert);
- scan.close();
- String sql = "SELECT * FROM REGISTRATION;";
- ResultSet rs = stmt.executeQuery(sql); // rs olioon palautuu tietuejoukko
- while (rs.next())
- {
- int id = rs.getInt("id");
- String firstName = rs.getString("first");
- String lastName = rs.getString("last");
- int age = rs.getInt("age");
- // print the results
- System.out.format("%s, %s, %s, %s\n", id, firstName, lastName, age);
- }
- stmt.close();
- }
- catch (SQLException se) {
- se.printStackTrace();
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- finally {
- try {
- if (stmt != null) {
- conn.close();
- }
- }
- catch (SQLException se) {
- }
- try {
- if (conn != null) {
- conn.close();
- }
- } catch (SQLException se) {
- se.printStackTrace();
- }
- }
- System.out.println("Goodbye!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement