├── .gitignore
├── LICENSE.md
├── Readme.txt
├── pom.xml
└── src
└── main
├── java
├── jdbc
│ ├── basics
│ │ ├── Ex_1_FirstConnection.java
│ │ ├── Ex_2_CreateAndDropTable.java
│ │ └── Ex_3_TooManyConnections.java
│ ├── cursors
│ │ ├── Ex_10_InsertingRow.java
│ │ ├── Ex_8_CursorJumping.java
│ │ └── Ex_9_UpdateRow.java
│ ├── metadata
│ │ └── Ex_16_DatabaseMetadata.java
│ ├── rowset
│ │ ├── Ex_17_RowSetSelect.java
│ │ └── Ex_18_RowSetSelectWithListener.java
│ ├── statements
│ │ ├── Ex_4_SelectCustomers.java
│ │ ├── Ex_5_SelectCustomers_Java_7.java
│ │ ├── Ex_6_PreparedStatement.java
│ │ └── Ex_7_StoredProcedure.java
│ └── transactions
│ │ ├── Ex_11_ChangeSex.java
│ │ ├── Ex_12_ChangeSexInOneBatch.java
│ │ ├── Ex_13_ChangeSexInOneTransaction.java
│ │ ├── Ex_14_ChangeSexInOneTransaction_Java_7.java
│ │ └── Ex_15_ChangeSexInOneTransactionWithSavepoints.java
└── spring_jdbc
│ ├── Product.java
│ ├── ShopDao.java
│ └── SpringApp.java
└── resources
├── beans.xml
├── jdbc.properties
└── shop.sql
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Java template
3 | *.class
4 |
5 | # BlueJ files
6 | *.ctxt
7 |
8 | # Mobile Tools for Java (J2ME)
9 | .mtj.tmp/
10 |
11 | # Package Files #
12 | *.jar
13 | *.war
14 | *.ear
15 |
16 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
17 | hs_err_pid*
18 | ### Maven template
19 | target/
20 | pom.xml.tag
21 | pom.xml.releaseBackup
22 | pom.xml.versionsBackup
23 | pom.xml.next
24 | release.properties
25 | dependency-reduced-pom.xml
26 | buildNumber.properties
27 | .mvn/timing.properties
28 |
29 | # Exclude maven wrapper
30 | !/.mvn/wrapper/maven-wrapper.jar
31 | ### Example user template template
32 | ### Example user template
33 |
34 | # IntelliJ project files
35 | .idea
36 | *.iml
37 | out
38 | gen
39 | .gitignore
40 | .idea/
41 | JDBC_Tutorial.iml
42 |
43 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2016 Zinoviev Alexey
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/Readme.txt:
--------------------------------------------------------------------------------
1 | If you are really interesting in JDBC API usage you can find a lot of examples in this repository
2 |
3 | All these examples can be run with database 'shop' .
4 |
5 | Database can be imported from shop.sql (in resource folder)
6 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 | * Also you are able to insert row in the last position using .insertRow() 10 | */ 11 | public class Ex_10_InsertingRow { 12 | 13 | public static final String URL = "jdbc:mysql://localhost:3306/"; 14 | public static final String DB_NAME = "shop"; 15 | public static final String USER_NAME = "root"; 16 | public static final String PASSWORD = "pass"; 17 | 18 | 19 | public static void main(String[] args) throws SQLException { 20 | 21 | try (Connection connection = getConnection(DB_NAME); 22 | PreparedStatement st = connection.prepareStatement("SELECT * FROM products", 23 | ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY)) { //Solution: FIX and change to ResultSet.CONCUR_UPDATEBABLE 24 | 25 | 26 | ResultSet rs = st.executeQuery(); 27 | System.out.println("DESC ORDER"); 28 | rs.last(); 29 | rs.moveToInsertRow(); 30 | rs.updateInt(1, 10); 31 | rs.updateString(2, "Newest Toy"); 32 | rs.updateInt(3, 888); 33 | rs.insertRow(); 34 | 35 | rs.beforeFirst(); 36 | while (rs.next()) { 37 | System.out.println(rs.getRow() + ". " + rs.getString(2) 38 | + "\t" + rs.getString(3)); 39 | } 40 | 41 | } catch (SQLException e) { 42 | e.printStackTrace(); 43 | } 44 | } 45 | 46 | private static Connection getConnection(String databaseName) throws SQLException { 47 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/jdbc/cursors/Ex_8_CursorJumping.java: -------------------------------------------------------------------------------- 1 | package jdbc.cursors; 2 | 3 | import java.sql.*; 4 | 5 | /** 6 | * This example demonstrates strange behavior of TYPE_FORWARD_ONLY cursor with JDBC-MySQL driver 7 | * Yes, you can scroll it 8 | */ 9 | public class Ex_8_CursorJumping { 10 | 11 | public static final String URL = "jdbc:mysql://localhost:3306/"; 12 | public static final String DB_NAME = "shop"; 13 | public static final String USER_NAME = "root"; 14 | public static final String PASSWORD = "pass"; 15 | 16 | 17 | public static void main(String[] args) throws SQLException { 18 | 19 | try (Connection connection = getConnection(DB_NAME); 20 | PreparedStatement st = connection.prepareStatement("SELECT * FROM products", 21 | ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { 22 | 23 | 24 | ResultSet rs = st.executeQuery(); 25 | rs.first(); 26 | System.out.println("First " + rs.getRow() + ". " + rs.getString(2) 27 | + "\t" + rs.getString(3)); 28 | rs.last(); 29 | System.out.println("Last " + rs.getRow() + ". " + rs.getString(2) 30 | + "\t" + rs.getString(3)); 31 | 32 | rs.afterLast(); 33 | 34 | System.out.println("DESC ORDER"); 35 | while (rs.previous()) { 36 | System.out.println(rs.getRow() + ". " + rs.getString(2) 37 | + "\t" + rs.getString(3)); 38 | } 39 | 40 | } catch (SQLException e) { 41 | e.printStackTrace(); 42 | } 43 | } 44 | 45 | private static Connection getConnection(String databaseName) throws SQLException { 46 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/jdbc/cursors/Ex_9_UpdateRow.java: -------------------------------------------------------------------------------- 1 | package jdbc.cursors; 2 | 3 | import java.sql.*; 4 | 5 | /** 6 | * This example contains an error in PreparedStatement initialization 7 | * Fix it, choose correct parameter 8 | *
9 | * Also you are able to update row in the last position using .insertRow()
10 | */
11 | public class Ex_9_UpdateRow {
12 |
13 | public static final String URL = "jdbc:mysql://localhost:3306/";
14 | public static final String DB_NAME = "shop";
15 | public static final String USER_NAME = "root";
16 | public static final String PASSWORD = "pass";
17 |
18 |
19 | public static void main(String[] args) throws SQLException {
20 |
21 | try (Connection connection = getConnection(DB_NAME);
22 | PreparedStatement st = connection.prepareStatement("SELECT * FROM products",
23 | ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY)) { //Solution: FIX and change to ResultSet.CONCUR_UPDATEBABLE
24 |
25 | ResultSet rs = st.executeQuery();
26 | System.out.println("DESC ORDER");
27 | rs.afterLast();
28 | while (rs.previous()) {
29 | int price = rs.getInt(3);
30 | rs.updateInt(3, price + 1);
31 | rs.updateRow();
32 | //rs.deleteRow(); <------ very sad operator but you can if you wish
33 | }
34 |
35 | while (rs.next()) {
36 | System.out.println(rs.getRow() + ". " + rs.getString(2)
37 | + "\t" + rs.getString(3));
38 | }
39 |
40 | } catch (SQLException e) {
41 | e.printStackTrace();
42 | }
43 | }
44 |
45 | private static Connection getConnection(String databaseName) throws SQLException {
46 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/metadata/Ex_16_DatabaseMetadata.java:
--------------------------------------------------------------------------------
1 | package jdbc.metadata;
2 |
3 | import java.sql.*;
4 |
5 | /**
6 | * WIth this example you can ship over tables and columns of selected database
7 | */
8 | public class Ex_16_DatabaseMetadata {
9 |
10 | public static final String URL = "jdbc:mysql://localhost:3306/";
11 | public static final String DB_NAME = "shop";
12 | public static final String USER_NAME = "root";
13 | public static final String PASSWORD = "pass";
14 |
15 |
16 | public static void main(String[] args) {
17 |
18 | Connection connection = null;
19 | ResultSet tables = null;
20 |
21 | try {
22 | connection = getConnection(DB_NAME);
23 | DatabaseMetaData dbMetaData = connection.getMetaData();
24 | System.out.println("DB " + dbMetaData.getDatabaseProductName()
25 | + " with driver " + dbMetaData.getDriverName()
26 | + " and max columns in GROUP BY " + dbMetaData.getMaxColumnsInGroupBy());
27 |
28 |
29 | tables = dbMetaData.getTables(null, null, null, null);
30 |
31 | while (tables.next()) {
32 | String tableName = tables.getString(3);
33 | System.out.println("Meta info about table " + tableName);
34 |
35 | ResultSet columns = dbMetaData.getColumns(null, null, tableName, null);
36 | while (columns.next()) {
37 | String name = columns.getString("COLUMN_NAME");
38 | String type = columns.getString("TYPE_NAME");
39 | int size = columns.getInt("COLUMN_SIZE");
40 |
41 | System.out.println("Column name: [" + name + "]; type: [" + type
42 | + "]; size: [" + size + "]");
43 | }
44 | }
45 |
46 |
47 | } catch (SQLException e) {
48 | e.printStackTrace();
49 | } finally {
50 | try {
51 | if (tables != null) {
52 | tables.close();
53 | }
54 | } catch (SQLException e) {
55 | e.printStackTrace();
56 | }
57 | try {
58 | if (connection != null) {
59 | connection.close();
60 | }
61 | } catch (SQLException e) {
62 | e.printStackTrace();
63 | }
64 | }
65 | }
66 |
67 | private static Connection getConnection(String databaseName) throws SQLException {
68 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/rowset/Ex_17_RowSetSelect.java:
--------------------------------------------------------------------------------
1 | package jdbc.rowset;
2 |
3 | import javax.sql.rowset.JdbcRowSet;
4 | import javax.sql.rowset.RowSetProvider;
5 | import java.sql.SQLException;
6 |
7 | /**
8 | * RowSet is a new word (since Java 5.0) in light-weight configuration of JDBC connection
9 | */
10 | public class Ex_17_RowSetSelect {
11 |
12 | public static final String URL = "jdbc:mysql://localhost:3306/";
13 | public static final String DB_NAME = "shop";
14 | public static final String USER_NAME = "root";
15 | public static final String PASSWORD = "pass";
16 |
17 |
18 | public static void main(String[] args) throws SQLException {
19 |
20 | try {
21 | JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
22 | rowSet.setUrl(URL + DB_NAME);
23 | rowSet.setPassword(PASSWORD);
24 | rowSet.setUsername(USER_NAME);
25 | rowSet.setCommand("SELECT * FROM customers WHERE sex = ?");
26 | rowSet.setString(1, "male");
27 | rowSet.execute();
28 | while (rowSet.next()) {
29 | System.out.println(rowSet.getRow() + " " + rowSet.getString(2));
30 | }
31 |
32 | } catch (SQLException e) {
33 | e.printStackTrace();
34 | }
35 | }
36 |
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/rowset/Ex_18_RowSetSelectWithListener.java:
--------------------------------------------------------------------------------
1 | package jdbc.rowset;
2 |
3 | import javax.sql.RowSetEvent;
4 | import javax.sql.RowSetListener;
5 | import javax.sql.rowset.JdbcRowSet;
6 | import javax.sql.rowset.RowSetProvider;
7 | import java.sql.SQLException;
8 |
9 | /**
10 | * Also, you can subscribe on next events like .rowSetChanged/.rowChanged/.cursorMoved
11 | */
12 | public class Ex_18_RowSetSelectWithListener {
13 |
14 | public static final String URL = "jdbc:mysql://localhost:3306/";
15 | public static final String DB_NAME = "shop";
16 | public static final String USER_NAME = "root";
17 | public static final String PASSWORD = "pass";
18 |
19 |
20 | public static void main(String[] args) throws SQLException {
21 |
22 | try {
23 | JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
24 | rowSet.setUrl(URL + DB_NAME);
25 | rowSet.setPassword(PASSWORD);
26 | rowSet.setUsername(USER_NAME);
27 | rowSet.setCommand("SELECT * FROM customers WHERE sex = ?");
28 | rowSet.setString(1, "male");
29 | rowSet.execute();
30 |
31 | rowSet.addRowSetListener(new RowSetListener() {
32 | @Override
33 | public void rowSetChanged(RowSetEvent event) {
34 | System.out.println("RowSet was changed");
35 | }
36 |
37 | @Override
38 | public void rowChanged(RowSetEvent event) {
39 | System.out.println("Row was changed");
40 | }
41 |
42 | @Override
43 | public void cursorMoved(RowSetEvent event) {
44 | System.out.println("Cursor was moved");
45 | }
46 | });
47 | while (rowSet.next()) {
48 | System.out.println(rowSet.getRow() + " " + rowSet.getString(2));
49 | }
50 |
51 | rowSet.setCommand("SELECT * FROM prices");
52 | rowSet.execute();
53 | rowSet.last();
54 | rowSet.deleteRow();
55 | while (rowSet.previous()) {
56 | System.out.println(rowSet.getRow() + " " + rowSet.getString(2));
57 | }
58 |
59 | } catch (SQLException e) {
60 | e.printStackTrace();
61 | }
62 | }
63 |
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/statements/Ex_4_SelectCustomers.java:
--------------------------------------------------------------------------------
1 | package jdbc.statements;
2 |
3 | import java.sql.*;
4 |
5 | /**
6 | * If you are really like checked exceptions
7 | * Try to drop throws SQLException in main() method
8 | */
9 | public class Ex_4_SelectCustomers {
10 |
11 | public static final String URL = "jdbc:mysql://localhost:3306/";
12 | public static final String DB_NAME = "shop";
13 | public static final String USER_NAME = "root";
14 | public static final String PASSWORD = "pass";
15 |
16 |
17 | public static void main(String[] args) throws SQLException //Task1: Drop throws section
18 | {
19 |
20 | Connection connection = null;
21 | Statement st = null;
22 | ResultSet rs = null;
23 |
24 | /*try {*/
25 | connection = getConnection(DB_NAME);
26 | st = connection.createStatement();
27 |
28 | rs = st.executeQuery("SELECT * FROM customers WHERE sex = 'male'");
29 | while (rs.next()) {
30 | System.out.println(rs.getRow() + " " + rs.getString(2) + " " + rs.getDate("birthdate").toLocalDate().getYear());
31 | }
32 | //Solution: Don't forget required handling of null/SQLExceptions
33 | /*} catch (SQLException e) {
34 | e.printStackTrace();
35 | } finally {
36 | try {
37 | if(rs!=null){
38 | rs.close();
39 | }
40 | } catch (SQLException e) {
41 | e.printStackTrace();
42 | }
43 | try {
44 | if(st!=null){
45 | st.close();
46 | }
47 | } catch (SQLException e) {
48 | e.printStackTrace();
49 | }
50 | try {
51 | if(connection!=null){
52 | connection.close();
53 | }
54 | } catch (SQLException e) {
55 | e.printStackTrace();
56 | }
57 | }*/
58 |
59 |
60 | }
61 |
62 | private static Connection getConnection(String databaseName) throws SQLException {
63 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/statements/Ex_5_SelectCustomers_Java_7.java:
--------------------------------------------------------------------------------
1 | package jdbc.statements;
2 |
3 | import java.sql.*;
4 |
5 | /**
6 | * It's time to go to Java 7. Remove ugly catch section and go ahead!
7 | *
8 | * Task 1: connection should be achievable in finally
9 | * Solution: Global reference:)
10 | */
11 | public class Ex_5_SelectCustomers_Java_7 {
12 |
13 | public static final String URL = "jdbc:mysql://localhost:3306/";
14 | public static final String DB_NAME = "shop";
15 | public static final String USER_NAME = "root";
16 | public static final String PASSWORD = "pass";
17 | // public static Connection connPool = null; //Let's make ref on connection
18 |
19 |
20 | public static void main(String[] args) throws SQLException {
21 |
22 | try (Connection connection = getConnection(DB_NAME); Statement st = connection.createStatement()) {
23 | ResultSet rs = st.executeQuery("SELECT * FROM customers WHERE sex = 'male'");
24 | while (rs.next()) {
25 | System.out.println(rs.getRow() + " " + rs.getString(2) + " " + rs.getDate("birthdate").toLocalDate().getYear());
26 | }
27 | // connPool = connection;
28 |
29 | } catch (SQLException e) {
30 | e.printStackTrace();
31 | } finally {
32 | //System.out.println(connPool.getCatalog());
33 | }
34 |
35 | }
36 |
37 | private static Connection getConnection(String databaseName) throws SQLException {
38 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/statements/Ex_6_PreparedStatement.java:
--------------------------------------------------------------------------------
1 | package jdbc.statements;
2 |
3 | import java.sql.*;
4 | import java.util.Random;
5 |
6 | /**
7 | * Very often we are trying to parametrize our SQL queries
8 | * Please use PreparedStatement for that
9 | */
10 | public class Ex_6_PreparedStatement {
11 |
12 | public static final String URL = "jdbc:mysql://localhost:3306/";
13 | public static final String DB_NAME = "shop";
14 | public static final String USER_NAME = "root";
15 | public static final String PASSWORD = "pass";
16 |
17 |
18 | public static void main(String[] args) throws SQLException {
19 |
20 | try (Connection connection = getConnection(DB_NAME); PreparedStatement st = connection.prepareStatement("SELECT * FROM customers WHERE sex = ?")) { // Prepare Statement
21 | for (int i = 0; i < 5; i++) {
22 | System.out.println("Round #" + i);
23 | st.setString(1, new Random().nextBoolean() ? "male" : "female"); // Randomize our choice
24 | ResultSet rs = st.executeQuery();
25 | while (rs.next()) {
26 | System.out.println(rs.getRow() + " " + rs.getString(2) + " " + rs.getDate("birthdate").toLocalDate().getYear());
27 | }
28 | }
29 |
30 |
31 | } catch (SQLException e) {
32 | e.printStackTrace();
33 | }
34 | }
35 |
36 | private static Connection getConnection(String databaseName) throws SQLException {
37 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/statements/Ex_7_StoredProcedure.java:
--------------------------------------------------------------------------------
1 | package jdbc.statements;
2 |
3 | import java.sql.*;
4 |
5 | /**
6 | * [NOTE] Before execution: Add stored procedure 'getAllGoods' to your MySQL database (Wrap SQL query 'SELECT * FROM products')
7 | *
8 | * This class calls stored procedure to print out all products from database
9 | *
10 | */
11 | public class Ex_7_StoredProcedure {
12 |
13 | public static final String URL = "jdbc:mysql://localhost:3306/";
14 | public static final String DB_NAME = "shop";
15 | public static final String USER_NAME = "root";
16 | public static final String PASSWORD = "pass";
17 |
18 | public static void main(String[] args) throws SQLException {
19 |
20 | try (Connection connection = getConnection(DB_NAME);
21 | CallableStatement st = connection.prepareCall("CALL getAllGoods")) { // Call StoredProcedure getAllGoods with body: SELECT * FROM shop.customers;
22 |
23 | ResultSet rs = st.executeQuery();
24 | while (rs.next()) {
25 | System.out.println(rs.getRow() + " " + rs.getString(2));
26 | }
27 |
28 | } catch (SQLException e) {
29 | e.printStackTrace();
30 | }
31 | }
32 |
33 | private static Connection getConnection(String databaseName) throws SQLException {
34 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/transactions/Ex_11_ChangeSex.java:
--------------------------------------------------------------------------------
1 | package jdbc.transactions;
2 |
3 | import java.sql.*;
4 | import java.util.Random;
5 |
6 | /**
7 | * It's time to change sex has gone
8 | */
9 | public class Ex_11_ChangeSex {
10 |
11 | public static final String URL = "jdbc:mysql://localhost:3306/";
12 | public static final String DB_NAME = "shop";
13 | public static final String USER_NAME = "root";
14 | public static final String PASSWORD = "pass";
15 |
16 |
17 | public static void main(String[] args) throws SQLException {
18 |
19 | try (Connection connection = getConnection(DB_NAME);
20 | PreparedStatement st = connection.prepareStatement("SELECT * FROM customers WHERE sex = ?");
21 | PreparedStatement updateSt = connection.prepareStatement("UPDATE customers SET sex = ? WHERE id = ?")) {
22 |
23 | // SELECT ALL MALES
24 | st.setString(1, "male");
25 | ResultSet rs = st.executeQuery();
26 | System.out.println("Men List");
27 | while (rs.next()) {
28 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
29 | + "\t" + rs.getString("lastname"));
30 | }
31 |
32 | // UPDATE SEX FOR ONE MAN AND ONE WOMAN
33 | updateSt.setString(1, "female");
34 | updateSt.setInt(2, 1);
35 | updateSt.executeUpdate();
36 |
37 | if (new Random().nextBoolean()) { // Sometimes shit happens, if you need it everytime use if(true)
38 | throw new RuntimeException();
39 | }
40 |
41 | updateSt.setString(1, "male");
42 | updateSt.setInt(2, 3);
43 | updateSt.executeUpdate();
44 |
45 | System.out.println("Sex was exchanged");
46 |
47 | // SELECT ALL FEMALES
48 | st.setString(1, "female");
49 | rs = st.executeQuery();
50 | System.out.println("Women List");
51 | while (rs.next()) {
52 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
53 | + "\t" + rs.getString("lastname"));
54 | }
55 |
56 | } catch (SQLException e) {
57 | e.printStackTrace();
58 | }
59 | }
60 |
61 | private static Connection getConnection(String databaseName) throws SQLException {
62 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/transactions/Ex_12_ChangeSexInOneBatch.java:
--------------------------------------------------------------------------------
1 | package jdbc.transactions;
2 |
3 | import java.sql.*;
4 | import java.util.Arrays;
5 |
6 | /**
7 | * Batch technique is very useful then you need deliver all statements together through the network
8 | * Don't forget to enable batch support for your Database
9 | */
10 | public class Ex_12_ChangeSexInOneBatch {
11 |
12 | public static final String URL = "jdbc:mysql://localhost:3306/";
13 | public static final String DB_NAME = "shop";
14 | public static final String USER_NAME = "root";
15 | public static final String PASSWORD = "pass";
16 |
17 |
18 | public static void main(String[] args) throws SQLException {
19 |
20 | try (Connection connection = getConnection(DB_NAME);
21 | PreparedStatement st = connection.prepareStatement("SELECT * FROM customers WHERE sex = ?");
22 | PreparedStatement updateSt = connection.prepareStatement("UPDATE customers SET sex = ? WHERE id = ?")) {
23 |
24 | // SELECT ALL MALES
25 | st.setString(1, "male");
26 | ResultSet rs = st.executeQuery();
27 | System.out.println("Men List");
28 | while (rs.next()) {
29 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
30 | + "\t" + rs.getString("lastname"));
31 | }
32 |
33 | // UPDATE SEX FOR ONE MAN AND ONE WOMAN
34 | updateSt.setString(1, "female");
35 | updateSt.setInt(2, 1);
36 | updateSt.addBatch();
37 |
38 |
39 | updateSt.setString(1, "male");
40 | updateSt.setInt(2, 3);
41 | updateSt.addBatch();
42 |
43 |
44 | updateSt.setString(1, "female");
45 | updateSt.setInt(2, 2);
46 | updateSt.addBatch();
47 |
48 | final int[] ints = updateSt.executeBatch();
49 | System.out.println("Batch results: " + Arrays.toString(ints));
50 |
51 | System.out.println("Sex was exchanged");
52 |
53 | // SELECT ALL FEMALES
54 | st.setString(1, "female");
55 | rs = st.executeQuery();
56 | System.out.println("Women List");
57 | while (rs.next()) {
58 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
59 | + "\t" + rs.getString("lastname"));
60 | }
61 |
62 | } catch (SQLException e) {
63 | e.printStackTrace();
64 | }
65 | }
66 |
67 | private static Connection getConnection(String databaseName) throws SQLException {
68 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/transactions/Ex_13_ChangeSexInOneTransaction.java:
--------------------------------------------------------------------------------
1 | package jdbc.transactions;
2 |
3 | import java.sql.*;
4 | import java.util.Random;
5 |
6 | /**
7 | * Sometimes we need change our sex together ...
8 | * In one transaction only
9 | */
10 | public class Ex_13_ChangeSexInOneTransaction {
11 |
12 | public static final String URL = "jdbc:mysql://localhost:3306/";
13 | public static final String DB_NAME = "shop";
14 | public static final String USER_NAME = "root";
15 | public static final String PASSWORD = "pass";
16 |
17 |
18 | public static void main(String[] args) throws SQLException {
19 |
20 | try (Connection connection = getConnection(DB_NAME);
21 | PreparedStatement st = connection.prepareStatement("SELECT * FROM customers WHERE sex = ?");
22 | PreparedStatement updateSt = connection.prepareStatement("UPDATE customers SET sex = ? WHERE id = ?")) {
23 |
24 | // SELECT ALL MALES
25 | st.setString(1, "male");
26 | ResultSet rs = st.executeQuery();
27 | System.out.println("Men List");
28 | while (rs.next()) {
29 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
30 | + "\t" + rs.getString("lastname"));
31 | }
32 |
33 | // UPDATE SEX FOR ONE MAN AND ONE WOMAN
34 | connection.setAutoCommit(false); //<---------- START TRANSACTION
35 | updateSt.setString(1, "female");
36 | updateSt.setInt(2, 1);
37 | updateSt.executeUpdate();
38 |
39 | if (new Random().nextBoolean()) { /* Sometimes shit happens */
40 | throw new SQLException();
41 | }
42 |
43 | updateSt.setString(1, "male");
44 | updateSt.setInt(2, 3);
45 | updateSt.executeUpdate();
46 |
47 | System.out.println("Sex was exchanged");
48 |
49 | // SELECT ALL FEMALES
50 | st.setString(1, "female");
51 | rs = st.executeQuery();
52 | System.out.println("Women List");
53 | while (rs.next()) {
54 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
55 | + "\t" + rs.getString("lastname"));
56 | }
57 | connection.commit(); //<------------ END TRANSACTION
58 |
59 | } catch (SQLException e) {
60 | e.printStackTrace();
61 | /* Trying to rollback transaction */
62 | //connection.rollback()
63 |
64 | /* According to the language spec,
65 | the connection will be closed before the catch clause is executed */
66 | }
67 | }
68 |
69 | private static Connection getConnection(String databaseName) throws SQLException {
70 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/transactions/Ex_14_ChangeSexInOneTransaction_Java_7.java:
--------------------------------------------------------------------------------
1 | package jdbc.transactions;
2 |
3 | import java.sql.*;
4 |
5 | /**
6 | * Of course, we are modern and sexy and can merge try-with-resources and transaction JDBC API
7 | */
8 | public class Ex_14_ChangeSexInOneTransaction_Java_7 {
9 |
10 | public static final String URL = "jdbc:mysql://localhost:3306/";
11 | public static final String DB_NAME = "shop";
12 | public static final String USER_NAME = "root";
13 | public static final String PASSWORD = "pass";
14 |
15 | public static void main(String[] args) throws SQLException {
16 |
17 | try (Connection connection = getConnection(DB_NAME)) {
18 | //connection.setAutoCommit(false); //SOLUTION <---------- START TRANSACTION
19 | try (PreparedStatement st = connection.prepareStatement("SELECT * FROM customerss WHERE sex = ?");
20 | //Solution "SELECT * FROM customers WHERE sex = ?"
21 | PreparedStatement updateSt = connection.prepareStatement("UPDATE customers SET sex = ? WHERE id = ?")) {
22 |
23 | // SELECT ALL MALES
24 | st.setString(1, "male");
25 | ResultSet rs = st.executeQuery();
26 | System.out.println("Men List");
27 | while (rs.next()) {
28 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
29 | + "\t" + rs.getString("lastname"));
30 | }
31 |
32 | // UPDATE SEX FOR ONE MAN AND ONE WOMAN
33 | connection.setAutoCommit(false); //<---------- START TRANSACTION with Exception in rollback
34 | updateSt.setString(1, "female");
35 | updateSt.setInt(2, 1);
36 | updateSt.executeUpdate();
37 |
38 | updateSt.setString(1, "male");
39 | updateSt.setInt(2, 3);
40 | updateSt.executeUpdate();
41 |
42 | System.out.println("Sex was exchanged");
43 |
44 | // SELECT ALL FEMALES
45 | st.setString(1, "female");
46 | rs = st.executeQuery();
47 | System.out.println("Women List");
48 | while (rs.next()) {
49 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
50 | + "\t" + rs.getString("lastname"));
51 | }
52 |
53 |
54 | connection.commit(); //<------------ END TRANSACTION
55 |
56 | } catch (SQLException e) {
57 | /* Trying to rollback transaction */
58 | connection.rollback();
59 | throw e;
60 | }
61 | } catch (SQLException e) {
62 | System.out.println("Second catch clause");
63 | e.printStackTrace();
64 | }
65 | }
66 |
67 | private static Connection getConnection(String databaseName) throws SQLException {
68 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/jdbc/transactions/Ex_15_ChangeSexInOneTransactionWithSavepoints.java:
--------------------------------------------------------------------------------
1 | package jdbc.transactions;
2 |
3 | import java.sql.*;
4 | import java.util.Random;
5 |
6 | /**
7 | * Let's return to Java 6 when we have deal with savepoints and jdbc.transactions
8 | */
9 | public class Ex_15_ChangeSexInOneTransactionWithSavepoints {
10 |
11 | public static final String URL = "jdbc:mysql://localhost:3306/";
12 | public static final String DB_NAME = "shop";
13 | public static final String USER_NAME = "root";
14 | public static final String PASSWORD = "pass";
15 |
16 | public static void main(String[] args) {
17 |
18 | Connection connection = null;
19 | PreparedStatement st = null;
20 | PreparedStatement updateSt = null;
21 | Savepoint savepoint = null;
22 |
23 | try {
24 | connection = getConnection(DB_NAME);
25 | st = connection.prepareStatement("SELECT * FROM customers WHERE sex = ?");
26 | updateSt = connection.prepareStatement("UPDATE customers SET sex = ? WHERE id = ?");
27 |
28 | connection.setAutoCommit(false);
29 |
30 | // SELECT ALL MALES
31 | st.setString(1, "male");
32 | ResultSet rs = st.executeQuery();
33 | System.out.println("Men List");
34 | while (rs.next()) {
35 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
36 | + "\t" + rs.getString("lastname"));
37 | }
38 |
39 | // UPDATE SEX FOR ONE MAN AND ONE WOMAN
40 | updateSt.setString(1, "female");
41 | updateSt.setInt(2, 1);
42 | updateSt.executeUpdate();
43 |
44 | savepoint = connection.setSavepoint("New_Female_was_born");
45 |
46 | if (new Random().nextBoolean()) { /* Sometimes shit happens */
47 | throw new SQLException("SQL was brokeeeeen");
48 | }
49 |
50 | updateSt.setString(1, "male");
51 | updateSt.setInt(2, 3);
52 | updateSt.executeUpdate();
53 |
54 | System.out.println("Sex was exchanged");
55 |
56 | // SELECT ALL FEMALES
57 | st.setString(1, "female");
58 | rs = st.executeQuery();
59 | System.out.println("Women List");
60 | while (rs.next()) {
61 | System.out.println(rs.getRow() + ". " + rs.getString("firstname")
62 | + "\t" + rs.getString("lastname"));
63 | }
64 |
65 |
66 | connection.commit(); //<------------ END TRANSACTION
67 |
68 | } catch (SQLException e) {
69 | e.printStackTrace();
70 | if (connection != null) {
71 | try {
72 | connection.rollback(savepoint);
73 | /*
74 | But first part of transaction (before savepoint) wasn't applied
75 | Solution: call connection.commit()
76 | */
77 | //connection.commit();
78 | } catch (SQLException e1) {
79 | e1.printStackTrace();
80 | }
81 |
82 | }
83 |
84 | } finally {
85 | if (connection != null) {
86 | try {
87 | connection.close();
88 | } catch (SQLException e) {
89 | e.printStackTrace();
90 | }
91 | }
92 | }
93 | }
94 |
95 | private static Connection getConnection(String databaseName) throws SQLException {
96 | return DriverManager.getConnection(URL + databaseName, USER_NAME, PASSWORD);
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/spring_jdbc/Product.java:
--------------------------------------------------------------------------------
1 | package spring_jdbc;
2 |
3 | /**
4 | * Created by Alexey_Zinovyev on 31-Oct-16.
5 | */
6 | public class Product {
7 |
8 | private String name;
9 | private int weight;
10 | private String category;
11 |
12 | public Product(String name, int weight, String category) {
13 | this.name = name;
14 | this.weight = weight;
15 | this.category = category;
16 | }
17 |
18 | public Product() {
19 | }
20 |
21 | public String getName() {
22 | return name;
23 | }
24 |
25 | public void setName(String name) {
26 | this.name = name;
27 | }
28 |
29 | public int getWeight() {
30 | return weight;
31 | }
32 |
33 | public void setWeight(int weight) {
34 | this.weight = weight;
35 | }
36 |
37 | public String getCategory() {
38 | return category;
39 | }
40 |
41 | public void setCategory(String category) {
42 | this.category = category;
43 | }
44 |
45 | @Override
46 | public String toString() {
47 | return "Product{" +
48 | "name='" + name + '\'' +
49 | ", weight=" + weight +
50 | ", category='" + category + '\'' +
51 | '}';
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/spring_jdbc/ShopDao.java:
--------------------------------------------------------------------------------
1 | package spring_jdbc;
2 |
3 | import org.springframework.jdbc.core.JdbcTemplate;
4 | import org.springframework.jdbc.core.RowMapper;
5 | import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
6 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
7 | import org.springframework.jdbc.core.namedparam.SqlParameterSource;
8 | import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
9 |
10 | import javax.sql.DataSource;
11 | import java.sql.ResultSet;
12 | import java.sql.SQLException;
13 | import java.util.List;
14 | import java.util.Map;
15 |
16 | /**
17 | * Created by Alexey_Zinovyev on 31-Oct-16.
18 | */
19 | public class ShopDao {
20 | private JdbcTemplate jdbcTemplate;
21 | private SimpleJdbcInsert insertTemplate;
22 | private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
23 |
24 | public void setDataSource(DataSource dataSource) { // <---- Inject DataSource through setter
25 | this.jdbcTemplate = new JdbcTemplate(dataSource);
26 | this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
27 | this.insertTemplate = new SimpleJdbcInsert(dataSource).withTableName("products");
28 | }
29 |
30 | public void insertProduct(Map