├── README.md └── src └── net └── javaguides └── jdbc ├── CountDuplicateCharacters.java ├── CountVowelsAndConsonants.java ├── FirstNonRepeatedCharacter.java ├── JdbcAutoGenKey.java ├── JdbcMySQLVersion.java ├── JdbcReadImage.java ├── JdbcWriteImage.java ├── RemoveGivenCharacter.java ├── crud ├── CreateStatementExample.java ├── InsertPStatementExample.java ├── JDBCUtils.java ├── SelectPStatementExample.java └── UpdatePStatementExample.java ├── h2 └── crud │ ├── H2CreateExample.java │ ├── H2DeleteExample.java │ ├── H2InsertExample.java │ ├── H2JDBCUtils.java │ ├── H2SelectExample.java │ └── H2UpdateExample.java └── hsqldb └── crud ├── HSQLDBCreateExample.java ├── HSQLDBDeleteExample.java ├── HSQLDBInsertExample.java ├── HSQLDBSelectExample.java ├── HSQLDBUpdateExample.java └── JDBCUtils.java /README.md: -------------------------------------------------------------------------------- 1 | # JDBC-4.2-Tutorial 2 | JDBC 4.2 Tutorial with Java 8 3 | 4 | 5 |
6 | 7 | This is complete beginners to expert up-to-date JDBC 4.2 Tutorial. In this tutorial, we will learn the latest features added to JDBC 4,4.1 and 4.2 release. All the source code examples in this tutorial are developed using JDK 8 with JDBC 4.2.
8 |
9 | JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.
10 |
11 | Java JDBC API Overview
12 |

13 | JDBC 4.2 API - Statement

14 | 17 |           Example to update a record in a table using Statement interface.
18 | 21 |           Example to insert multiple records in a table using Statement interface.
22 | 25 |           Example to create a table using Statement interface.
26 | 29 |           Example to retrieve records from a table using Statement interface.
30 | 33 |           Example to delete a record from a table using Statement interface.
34 | 37 |           Example to insert records in a batch process via Statement interface.
38 | 41 |           Example to update records in a batch process via Statement interface.
42 |

43 | JDBC 4.2 API - PreparedStatement

44 | 47 |          Example to insert a record in a table using PreparedStatement interface.
48 | 51 |          Example to update a record in a table using PreparedStatement interface.
52 | 55 |           Example to retrieve records from a table using PreparedStatement interface.
56 | 59 |           Example to pass a list of values to IN clause using PreparedStatement interface.
60 | 63 |           Example to insert records in a batch process via PreparedStatement interface.
64 | 67 |           Example to update records in a batch process via PreparedStatement interface.
68 |

69 | JDBC 4.2 API - CallableStatement

70 | 73 |           Create and use Stored Procedure examples using CallableStatement interface.
74 |

75 | JDBC 4.2 API - Transactions

76 | 79 |           How to use JDBC transactions with examples.
80 |

81 | JDBC 4.2 API - SQLExceptions Handling

82 | 85 |
86 |           In this article, we will learn how to handle SQLExceptions while working with JDBC.
87 |

88 | JDBC 4.2 API - java.sql Package

89 | 92 |
93 |           In this article, we will learn commonly used methods of Connection interface with examples.
94 | 97 |          In this article, we will learn commonly used methods of Statement interface with examples.
98 | 101 |           In this article, we will learn commonly used methods of PreparedStatement interface.
102 | 105 |           In this article, we will learn commonly used methods of CallableStatement interface.
106 | 109 |           In this article, we will learn commonly used methods of ResultSet interface with examples.
110 | 113 |           In this article, we will learn commonly used methods of ResultSetMetaData interface.
114 | 117 |           In this article, we will learn commonly used methods of DatabaseMetadata interface.
118 | 121 |           In this article, we will learn commonly used methods of DriverManager class with examples.
122 |

123 | JDBC 4.2 API - Batch Processing

124 | 127 |          Example to update records in a batch process using Statement and PreparedStatement interfaces.
128 | 131 |          Example to insert records in a batch process using Statement and PreparedStatement interfaces.
132 | 135 |           Example to insert records in a batch process via Statement interface.
136 | 139 |          Example to update records in a batch process via Statement interface.
140 | 143 |          Example to insert records in a batch process via PreparedStatement interface.
144 | 147 |           Example to update records in a batch process via PreparedStatement interface.
148 |

149 | JDBC 4.2 API FAQ

150 | 153 |          Example to dynamically insert rows using StringBuilder and PreparedStatement placeholders ?.
154 | 157 |          This article provides how to retrieve column names of a table using getMetaData() method.
158 | 161 |           Example of how to use DataSource to connect with MySQL database.
162 |

163 | Resource and Useful Links

164 |
165 |
166 |
167 | 170 | 173 | 176 | 179 | 182 | 185 | 188 | 191 | 194 | 197 | 200 |
201 |
202 | 205 | 208 |
209 |
210 |

211 | Reference

212 | 219 |
220 |
221 | 222 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/CountDuplicateCharacters.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.stream.Collectors; 8 | 9 | public class CountDuplicateCharacters { 10 | private static final String TEXT = "Java is a popular " 11 | + " general-purpose programming language " 12 | + "and computing platform. It is fast, reliable, and secure."; 13 | 14 | public static void main(String[] args) { 15 | 16 | System.out.println("Input text: \n" + TEXT + "\n"); 17 | 18 | System.out.println("HashMap based solution:"); 19 | Map duplicatesV1 = countDuplicateCharactersV1(TEXT); 20 | System.out.println(Arrays.toString(duplicatesV1.entrySet().toArray())); 21 | 22 | System.out.println(); 23 | System.out.println("Java 8, functional-style solution:"); 24 | Map duplicatesV2 = countDuplicateCharactersV2(TEXT); 25 | System.out.println(Arrays.toString(duplicatesV2.entrySet().toArray())); 26 | } 27 | 28 | public static Map countDuplicateCharactersV1(String str) { 29 | 30 | if (str == null) { 31 | // or throw IllegalArgumentException 32 | return Collections.EMPTY_MAP; 33 | } 34 | 35 | Map result = new HashMap<>(); 36 | 37 | for (int i = 0; i < str.length(); i++) { 38 | 39 | char ch = str.charAt(i); 40 | 41 | Integer count = result.get(ch); 42 | if (count != null) { 43 | result.put(ch, ++count); 44 | } else { 45 | result.put(ch, 1); 46 | } 47 | } 48 | 49 | return result; 50 | } 51 | 52 | public static Map countDuplicateCharactersV2(String str) { 53 | 54 | if (str == null) { 55 | // or throw IllegalArgumentException 56 | return Collections.EMPTY_MAP; 57 | } 58 | 59 | Map result = str.chars() 60 | .mapToObj(c -> (char) c) 61 | .collect(Collectors.groupingBy(c -> c, Collectors.counting())); 62 | 63 | return result; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/CountVowelsAndConsonants.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc; 2 | 3 | //# Count vowels and consonants 4 | public class CountVowelsAndConsonants { 5 | 6 | private static long vowels = 0; 7 | private static long consonants = 0; 8 | private static final String TEXT = "Java is Popular Programming Language"; 9 | 10 | public static void main(String[] args) { 11 | 12 | System.out.println("Input text: \n" + TEXT + "\n"); 13 | 14 | System.out.println("Java 8, functional-style solution:"); 15 | 16 | countVowelsAndConsonants(TEXT); 17 | 18 | System.out.println("Vowels: " + vowels); 19 | System.out.println("Consonants: " + consonants); 20 | 21 | } 22 | 23 | public static void countVowelsAndConsonants(String str) { 24 | 25 | if (str == null) { 26 | // or throw IllegalArgumentException 27 | throw new IllegalArgumentException("Input String can't be null"); 28 | } 29 | 30 | str = str.toLowerCase(); 31 | 32 | vowels = str.chars().filter(ch -> (ch == 'a' || ch == 'e' 33 | || ch == 'i' || ch == 'o' || ch == 'u')).count(); 34 | 35 | consonants = str.chars().filter(ch -> (ch != 'a' && ch != 'e' 36 | && ch != 'i' && ch != 'o' && ch != 'u')) 37 | .filter(ch -> (ch >= 'a' && ch <= 'z')).count(); 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/FirstNonRepeatedCharacter.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | import java.util.function.Function; 6 | import java.util.stream.Collectors; 7 | 8 | public class FirstNonRepeatedCharacter { 9 | 10 | private static final int EXTENDED_ASCII_CODES = 256; 11 | 12 | private static final String TEXT = "Java Guides Popular blog Website"; 13 | 14 | public static void main(String[] args) { 15 | 16 | System.out.println("Input text: \n" + TEXT + "\n"); 17 | 18 | System.out.println("Loop and break solution:"); 19 | char firstcharV1 = firstNonRepeatedCharacterV1(TEXT); 20 | 21 | System.out.println("Found character: " + firstcharV1); 22 | 23 | System.out.println(); 24 | System.out.println(" 256 ASCII codes solution:"); 25 | 26 | char firstcharV2 = firstNonRepeatedCharacterV2(TEXT); 27 | System.out.println("Found character: " + firstcharV2); 28 | 29 | System.out.println(); 30 | System.out.println("LinkedHashMap based solution:"); 31 | char firstcharV3 = firstNonRepeatedCharacterV3(TEXT); 32 | System.out.println("Found character: " + firstcharV3); 33 | 34 | System.out.println(); 35 | System.out.println("Java 8, functional-style solution:"); 36 | char firstcharV4 = firstNonRepeatedCharacterV4(TEXT); 37 | System.out.println("Found character: " + firstcharV4); 38 | } 39 | 40 | public static char firstNonRepeatedCharacterV1(String str) { 41 | 42 | if (str == null) { 43 | // or throw IllegalArgumentException 44 | return Character.MIN_VALUE; 45 | } 46 | 47 | for (int i = 0; i < str.length(); i++) { 48 | 49 | char ch = str.charAt(i); 50 | 51 | int count = 0; 52 | for (int j = 0; j < str.length(); j++) { 53 | if (ch == str.charAt(j) && i != j) { 54 | count++; 55 | break; 56 | } 57 | } 58 | 59 | if (count == 0) { 60 | return ch; 61 | } 62 | } 63 | 64 | return Character.MIN_VALUE; 65 | } 66 | 67 | public static char firstNonRepeatedCharacterV2(String str) { 68 | 69 | if (str == null) { 70 | // or throw IllegalArgumentException 71 | return Character.MIN_VALUE; 72 | } 73 | 74 | int[] flags = new int[EXTENDED_ASCII_CODES]; 75 | 76 | for (int i = 0; i < flags.length; i++) { 77 | flags[i] = -1; 78 | } 79 | 80 | for (int i = 0; i < str.length(); i++) { 81 | 82 | if (flags[str.charAt(i)] == -1) { 83 | flags[str.charAt(i)] = i; 84 | } else { 85 | flags[str.charAt(i)] = -2; 86 | } 87 | } 88 | 89 | int position = Integer.MAX_VALUE; 90 | for (int i = 0; i < EXTENDED_ASCII_CODES; i++) { 91 | if (flags[i] >= 0) { 92 | position = Math.min(position, flags[i]); 93 | } 94 | } 95 | 96 | return position == Integer.MAX_VALUE ? Character.MIN_VALUE : str.charAt(position); 97 | } 98 | 99 | public static char firstNonRepeatedCharacterV3(String str) { 100 | 101 | if (str == null) { 102 | // or throw IllegalArgumentException 103 | return Character.MIN_VALUE; 104 | } 105 | 106 | Map chars = new LinkedHashMap<>(); 107 | 108 | for (int i = 0; i < str.length(); i++) { 109 | char ch = str.charAt(i); 110 | 111 | Integer count = chars.get(ch); 112 | if (count == null) { 113 | chars.put(ch, 1); 114 | } else { 115 | chars.put(ch, ++count); 116 | } 117 | } 118 | 119 | for (Map.Entry entry : chars.entrySet()) { 120 | if (entry.getValue() == 1) { 121 | return entry.getKey(); 122 | } 123 | } 124 | 125 | return Character.MIN_VALUE; 126 | } 127 | 128 | public static char firstNonRepeatedCharacterV4(String str) { 129 | 130 | if (str == null) { 131 | // or throw IllegalArgumentException 132 | return Character.MIN_VALUE; 133 | } 134 | 135 | Map chs = str.chars().boxed() 136 | .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())); 137 | 138 | return (char) (int) chs.entrySet().stream().filter(e -> e.getValue() == 1L).findFirst().map(Map.Entry::getKey) 139 | .orElse(Integer.valueOf(Character.MIN_VALUE)); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/JdbcAutoGenKey.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.PreparedStatement; 6 | import java.sql.ResultSet; 7 | import java.sql.SQLException; 8 | import java.sql.Statement; 9 | import java.util.logging.Level; 10 | import java.util.logging.Logger; 11 | 12 | public class JdbcAutoGenKey { 13 | 14 | public static void main(String[] args) { 15 | 16 | String url = "jdbc:mysql://localhost:3306/demo?useSSL=false"; 17 | String user = "root"; 18 | String password = "root"; 19 | 20 | String studentName = "Ramesh Fadatare"; 21 | String sql = "INSERT INTO Students(Name) VALUES(?)"; 22 | 23 | try (Connection con = DriverManager.getConnection(url, user, password); 24 | PreparedStatement preparedStatement = con.prepareStatement(sql, 25 | Statement.RETURN_GENERATED_KEYS)) { 26 | 27 | preparedStatement.setString(1, studentName); 28 | preparedStatement.executeUpdate(); 29 | 30 | try (ResultSet resultSet = preparedStatement.getGeneratedKeys()) { 31 | 32 | if (resultSet.first()) { 33 | 34 | System.out.printf("The ID of new student : %d", resultSet.getLong(1)); 35 | } 36 | } 37 | 38 | } catch (SQLException ex) { 39 | 40 | Logger lgr = Logger.getLogger(JdbcAutoGenKey.class.getName()); 41 | lgr.log(Level.SEVERE, ex.getMessage(), ex); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/JdbcMySQLVersion.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import java.sql.Statement; 8 | import java.util.logging.Level; 9 | import java.util.logging.Logger; 10 | 11 | public class JdbcMySQLVersion { 12 | 13 | public static void main(String[] args) { 14 | 15 | String url = "jdbc:mysql://localhost:3306/demo?useSSL=false"; 16 | String user = "root"; 17 | String password = "root"; 18 | 19 | String query = "SELECT VERSION()"; 20 | 21 | try (Connection con = DriverManager.getConnection(url, user, password); 22 | Statement st = con.createStatement(); 23 | ResultSet rs = st.executeQuery(query)) { 24 | 25 | if (rs.next()) { 26 | 27 | System.out.println(rs.getString(1)); 28 | } 29 | 30 | } catch (SQLException ex) { 31 | 32 | Logger lgr = Logger.getLogger(JdbcMySQLVersion.class.getName()); 33 | lgr.log(Level.SEVERE, ex.getMessage(), ex); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/JdbcReadImage.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.IOException; 5 | import java.sql.Blob; 6 | import java.sql.Connection; 7 | import java.sql.DriverManager; 8 | import java.sql.PreparedStatement; 9 | import java.sql.ResultSet; 10 | import java.sql.SQLException; 11 | import java.util.logging.Level; 12 | import java.util.logging.Logger; 13 | 14 | /** 15 | * Retrieve Image from MySQL Database Table using Java 16 | * @author Ramesh Fadatare 17 | * 18 | */ 19 | public class JdbcReadImage { 20 | 21 | public static void main(String[] args) { 22 | 23 | String url = "jdbc:mysql://localhost:3306/java_demo?useSSL=false"; 24 | String user = "root"; 25 | String password = "root"; 26 | 27 | String query = "SELECT Data FROM Images where id = 2"; 28 | 29 | try (Connection con = DriverManager.getConnection(url, user, password); PreparedStatement pst = con.prepareStatement(query); ResultSet result = pst.executeQuery()) { 30 | 31 | if (result.next()) { 32 | 33 | String fileName = "image1.png"; 34 | 35 | try (FileOutputStream fos = new FileOutputStream(fileName)) { 36 | 37 | Blob blob = result.getBlob("Data"); 38 | int len = (int) blob.length(); 39 | 40 | byte[] buf = blob.getBytes(1, len); 41 | 42 | fos.write(buf, 0, len); 43 | 44 | } catch (IOException ex) { 45 | 46 | Logger lgr = Logger.getLogger(JdbcReadImage.class.getName()); 47 | lgr.log(Level.SEVERE, ex.getMessage(), ex); 48 | } 49 | } 50 | } catch (SQLException ex) { 51 | 52 | Logger lgr = Logger.getLogger(JdbcReadImage.class.getName()); 53 | lgr.log(Level.SEVERE, ex.getMessage(), ex); 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/JdbcWriteImage.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.IOException; 6 | import java.sql.Connection; 7 | import java.sql.DriverManager; 8 | import java.sql.PreparedStatement; 9 | import java.sql.SQLException; 10 | import java.util.logging.Level; 11 | import java.util.logging.Logger; 12 | 13 | /** 14 | * Class demonstrate Inserting Image into MySQL Database using Java 15 | * @author Ramesh Fadatare 16 | * 17 | */ 18 | public class JdbcWriteImage { 19 | 20 | public static void main(String[] args) throws ClassNotFoundException { 21 | 22 | String url = "jdbc:mysql://localhost:3306/java_demo?useSSL=false"; 23 | String user = "root"; 24 | String password = "root"; 25 | 26 | String sql = "INSERT INTO Images(Data) VALUES(?)"; 27 | 28 | try (Connection con = DriverManager.getConnection(url, user, password); 29 | PreparedStatement pst = con.prepareStatement(sql)) { 30 | 31 | File myFile = new File("image.png"); 32 | try (FileInputStream fin = new FileInputStream(myFile)) { 33 | 34 | pst.setBinaryStream(1, fin, (int) myFile.length()); 35 | pst.executeUpdate(); 36 | 37 | } catch (IOException ex) { 38 | 39 | Logger lgr = Logger.getLogger(JdbcWriteImage.class.getName()); 40 | lgr.log(Level.SEVERE, ex.getMessage(), ex); 41 | } 42 | } catch (SQLException ex) { 43 | 44 | Logger lgr = Logger.getLogger(JdbcWriteImage.class.getName()); 45 | lgr.log(Level.SEVERE, ex.getMessage(), ex); 46 | } 47 | 48 | System.out.println("Image inserted successfully...."); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/RemoveGivenCharacter.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc; 2 | 3 | import java.util.regex.Pattern; 4 | import java.util.stream.Collectors; 5 | 6 | // # Remove given character 7 | public class RemoveGivenCharacter { 8 | private static final String TEXT = "JaAVaA GUIDES"; 9 | private static final char CHAR = 'a'; 10 | 11 | public static void main(String[] args) { 12 | 13 | System.out.println("Input text: \n" + TEXT); 14 | System.out.println("Character to remove: " + CHAR + "\n"); 15 | 16 | System.out.println("StringBuilder based solution:"); 17 | String resultV1 = removeCharacterV1(TEXT, CHAR); 18 | System.out.println("Result: \n" + resultV1); 19 | 20 | System.out.println(); 21 | System.out.println("Regular expression based solution:"); 22 | String resultV2 = removeCharacterV2(TEXT, CHAR); 23 | System.out.println("Result: \n" + resultV2); 24 | 25 | System.out.println(); 26 | System.out.println("Java 8, functional-style solution:"); 27 | String resultV3 = removeCharacterV3(TEXT, CHAR); 28 | System.out.println("Result: \n" + resultV3); 29 | } 30 | 31 | public static String removeCharacterV1(String str, char ch) { 32 | 33 | if (str == null || str.isEmpty()) { 34 | // or throw IllegalArgumentException 35 | throw new IllegalArgumentException("Input String can't be null"); 36 | } 37 | 38 | StringBuilder sb = new StringBuilder(); 39 | char[] chArray = str.toCharArray(); 40 | for (int i = 0; i < chArray.length; i++) { 41 | if (chArray[i] != ch) { 42 | sb.append(chArray[i]); 43 | } 44 | } 45 | 46 | return sb.toString(); 47 | } 48 | 49 | public static String removeCharacterV2(String str, char ch) { 50 | 51 | if (str == null || str.isEmpty()) { 52 | // or throw IllegalArgumentException 53 | throw new IllegalArgumentException("Input String can't be null"); 54 | } 55 | 56 | return str.replaceAll(Pattern.quote(String.valueOf(ch)), ""); 57 | } 58 | 59 | public static String removeCharacterV3(String str, char ch) { 60 | 61 | if (str == null || str.isEmpty()) { 62 | // or throw IllegalArgumentException 63 | throw new IllegalArgumentException("Input String can't be null"); 64 | } 65 | 66 | return str.chars().filter(c -> c != ch).mapToObj(c -> String.valueOf((char) c)).collect(Collectors.joining()); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/crud/CreateStatementExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | import java.sql.Statement; 7 | 8 | /** 9 | * Create Statement JDBC Example 10 | * @author Ramesh Fadatare 11 | * 12 | */ 13 | public class CreateStatementExample { 14 | 15 | private static final String createTableSQL = "create table users (\r\n" + " id int(3) primary key,\r\n" + 16 | " name varchar(20),\r\n" + " email varchar(20),\r\n" + " country varchar(20),\r\n" + 17 | " password varchar(20)\r\n" + " );"; 18 | 19 | public static void main(String[] argv) throws SQLException { 20 | CreateStatementExample createTableExample = new CreateStatementExample(); 21 | createTableExample.createTable(); 22 | } 23 | 24 | public void createTable() throws SQLException { 25 | 26 | System.out.println(createTableSQL); 27 | // Step 1: Establishing a Connection 28 | try (Connection connection = JDBCUtils.getConnection(); 29 | // Step 2:Create a statement using connection object 30 | Statement statement = connection.createStatement();) { 31 | 32 | // Step 3: Execute the query or update query 33 | statement.execute(createTableSQL); 34 | } catch (SQLException e) { 35 | 36 | // print SQL exception information 37 | JDBCUtils.printSQLException(e); 38 | } 39 | 40 | // Step 4: try-with-resource statement will auto close the connection. 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/crud/InsertPStatementExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.PreparedStatement; 6 | import java.sql.SQLException; 7 | 8 | /** 9 | * Insert PrepareStatement JDBC Example 10 | * 11 | * @author Ramesh Fadatare 12 | * 13 | */ 14 | public class InsertPStatementExample { 15 | private static final String INSERT_USERS_SQL = "INSERT INTO users" + 16 | " (id, name, email, country, password) VALUES " + 17 | " (?, ?, ?, ?, ?);"; 18 | 19 | public static void main(String[] argv) throws SQLException { 20 | InsertPStatementExample createTableExample = new InsertPStatementExample(); 21 | createTableExample.insertRecord(); 22 | } 23 | 24 | public void insertRecord() throws SQLException { 25 | System.out.println(INSERT_USERS_SQL); 26 | // Step 1: Establishing a Connection 27 | try (Connection connection = JDBCUtils.getConnection(); 28 | // Step 2:Create a statement using connection object 29 | PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) { 30 | preparedStatement.setInt(1, 1); 31 | preparedStatement.setString(2, "Tony"); 32 | preparedStatement.setString(3, "tony@gmail.com"); 33 | preparedStatement.setString(4, "US"); 34 | preparedStatement.setString(5, "secret"); 35 | 36 | System.out.println(preparedStatement); 37 | // Step 3: Execute the query or update query 38 | preparedStatement.executeUpdate(); 39 | } catch (SQLException e) { 40 | 41 | // print SQL exception information 42 | JDBCUtils.printSQLException(e); 43 | } 44 | 45 | // Step 4: try-with-resource statement will auto close the connection. 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/crud/JDBCUtils.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | 7 | public class JDBCUtils { 8 | 9 | private static String jdbcURL = "jdbc:mysql://localhost:3306/java_demo?useSSL=false"; 10 | private static String jdbcUsername = "root"; 11 | private static String jdbcPassword = "root"; 12 | 13 | public static Connection getConnection() { 14 | Connection connection = null; 15 | try { 16 | connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword); 17 | } catch (SQLException e) { 18 | // TODO Auto-generated catch block 19 | e.printStackTrace(); 20 | } 21 | return connection; 22 | } 23 | 24 | public static void printSQLException(SQLException ex) { 25 | for (Throwable e : ex) { 26 | if (e instanceof SQLException) { 27 | e.printStackTrace(System.err); 28 | System.err.println("SQLState: " + ((SQLException) e).getSQLState()); 29 | System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); 30 | System.err.println("Message: " + e.getMessage()); 31 | Throwable t = ex.getCause(); 32 | while (t != null) { 33 | System.out.println("Cause: " + t); 34 | t = t.getCause(); 35 | } 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/crud/SelectPStatementExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.PreparedStatement; 6 | import java.sql.ResultSet; 7 | import java.sql.SQLException; 8 | 9 | /** 10 | * Select PreparedStatement JDBC Example 11 | * 12 | * @author Ramesh Fadatare 13 | * 14 | */ 15 | public class SelectPStatementExample { 16 | private static final String QUERY = "select id,name,email,country,password from users where id =?"; 17 | 18 | public static void main(String[] args) { 19 | 20 | // using try-with-resources to avoid closing resources (boiler plate code) 21 | 22 | // Step 1: Establishing a Connection 23 | try (Connection connection = JDBCUtils.getConnection(); 24 | 25 | // Step 2:Create a statement using connection object 26 | PreparedStatement preparedStatement = connection.prepareStatement(QUERY);) { 27 | preparedStatement.setInt(1, 1); 28 | System.out.println(preparedStatement); 29 | // Step 3: Execute the query or update query 30 | ResultSet rs = preparedStatement.executeQuery(); 31 | 32 | // Step 4: Process the ResultSet object. 33 | while (rs.next()) { 34 | int id = rs.getInt("id"); 35 | String name = rs.getString("name"); 36 | String email = rs.getString("email"); 37 | String country = rs.getString("country"); 38 | String password = rs.getString("password"); 39 | System.out.println(id + "," + name + "," + email + "," + country + "," + password); 40 | } 41 | } catch (SQLException e) { 42 | JDBCUtils.printSQLException(e); 43 | } 44 | // Step 4: try-with-resource statement will auto close the connection. 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/crud/UpdatePStatementExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.PreparedStatement; 6 | import java.sql.SQLException; 7 | 8 | /** 9 | * Update PreparedStatement JDBC Example 10 | * @author Ramesh Fadatare 11 | * 12 | */ 13 | public class UpdatePStatementExample { 14 | 15 | private static final String UPDATE_USERS_SQL = "update users set name = ? where id = ?;"; 16 | 17 | public static void main(String[] argv) throws SQLException { 18 | UpdatePStatementExample updateStatementExample = new UpdatePStatementExample(); 19 | updateStatementExample.updateRecord(); 20 | } 21 | 22 | public void updateRecord() throws SQLException { 23 | System.out.println(UPDATE_USERS_SQL); 24 | // Step 1: Establishing a Connection 25 | try (Connection connection = JDBCUtils.getConnection(); 26 | // Step 2:Create a statement using connection object 27 | PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USERS_SQL)) { 28 | preparedStatement.setString(1, "Ram"); 29 | preparedStatement.setInt(2, 1); 30 | 31 | // Step 3: Execute the query or update query 32 | preparedStatement.executeUpdate(); 33 | } catch (SQLException e) { 34 | 35 | // print SQL exception information 36 | JDBCUtils.printSQLException(e); 37 | } 38 | 39 | // Step 4: try-with-resource statement will auto close the connection. 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/h2/crud/H2CreateExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.h2.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.SQLException; 5 | import java.sql.Statement; 6 | 7 | /** 8 | * Create Statement JDBC Example 9 | * @author Ramesh Fadatare 10 | * 11 | */ 12 | public class H2CreateExample { 13 | 14 | private static final String createTableSQL = "create table users (\r\n" + " id int(3) primary key,\r\n" + 15 | " name varchar(20),\r\n" + " email varchar(20),\r\n" + " country varchar(20),\r\n" + 16 | " password varchar(20)\r\n" + " );"; 17 | 18 | public static void main(String[] argv) throws SQLException { 19 | H2CreateExample createTableExample = new H2CreateExample(); 20 | createTableExample.createTable(); 21 | } 22 | 23 | public void createTable() throws SQLException { 24 | 25 | System.out.println(createTableSQL); 26 | // Step 1: Establishing a Connection 27 | try (Connection connection = H2JDBCUtils.getConnection(); 28 | // Step 2:Create a statement using connection object 29 | Statement statement = connection.createStatement();) { 30 | 31 | // Step 3: Execute the query or update query 32 | statement.execute(createTableSQL); 33 | } catch (SQLException e) { 34 | // print SQL exception information 35 | H2JDBCUtils.printSQLException(e); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/h2/crud/H2DeleteExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.h2.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.SQLException; 5 | import java.sql.Statement; 6 | 7 | public class H2DeleteExample { 8 | private static final String deleteTableSQL = "delete from users where id = 1"; 9 | 10 | public static void main(String[] argv) throws SQLException { 11 | H2DeleteExample deleteExample = new H2DeleteExample(); 12 | deleteExample.deleteRecord(); 13 | } 14 | 15 | public void deleteRecord() throws SQLException { 16 | 17 | System.out.println(deleteTableSQL); 18 | // Step 1: Establishing a Connection 19 | try (Connection connection = H2JDBCUtils.getConnection(); 20 | // Step 2:Create a statement using connection object 21 | Statement statement = connection.createStatement();) { 22 | 23 | // Step 3: Execute the query or update query 24 | statement.execute(deleteTableSQL); 25 | 26 | } catch (SQLException e) { 27 | // print SQL exception information 28 | H2JDBCUtils.printSQLException(e); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/h2/crud/H2InsertExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.h2.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.SQLException; 6 | 7 | /** 8 | * Insert PrepareStatement JDBC Example 9 | * 10 | * @author Ramesh Fadatare 11 | * 12 | */ 13 | public class H2InsertExample { 14 | private static final String INSERT_USERS_SQL = "INSERT INTO users" + 15 | " (id, name, email, country, password) VALUES " + 16 | " (?, ?, ?, ?, ?);"; 17 | 18 | public static void main(String[] argv) throws SQLException { 19 | H2InsertExample createTableExample = new H2InsertExample(); 20 | createTableExample.insertRecord(); 21 | } 22 | 23 | public void insertRecord() throws SQLException { 24 | System.out.println(INSERT_USERS_SQL); 25 | // Step 1: Establishing a Connection 26 | try (Connection connection = H2JDBCUtils.getConnection(); 27 | // Step 2:Create a statement using connection object 28 | PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) { 29 | preparedStatement.setInt(1, 1); 30 | preparedStatement.setString(2, "Tony"); 31 | preparedStatement.setString(3, "tony@gmail.com"); 32 | preparedStatement.setString(4, "US"); 33 | preparedStatement.setString(5, "secret"); 34 | 35 | System.out.println(preparedStatement); 36 | // Step 3: Execute the query or update query 37 | preparedStatement.executeUpdate(); 38 | } catch (SQLException e) { 39 | 40 | // print SQL exception information 41 | H2JDBCUtils.printSQLException(e); 42 | } 43 | 44 | // Step 4: try-with-resource statement will auto close the connection. 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/h2/crud/H2JDBCUtils.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.h2.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | 7 | public class H2JDBCUtils { 8 | 9 | private static String jdbcURL = "jdbc:h2:~/test1"; 10 | private static String jdbcUsername = "sa"; 11 | private static String jdbcPassword = ""; 12 | 13 | public static Connection getConnection() { 14 | Connection connection = null; 15 | try { 16 | connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword); 17 | } catch (SQLException e) { 18 | // TODO Auto-generated catch block 19 | e.printStackTrace(); 20 | } 21 | return connection; 22 | } 23 | 24 | public static void printSQLException(SQLException ex) { 25 | for (Throwable e : ex) { 26 | if (e instanceof SQLException) { 27 | e.printStackTrace(System.err); 28 | System.err.println("SQLState: " + ((SQLException) e).getSQLState()); 29 | System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); 30 | System.err.println("Message: " + e.getMessage()); 31 | Throwable t = ex.getCause(); 32 | while (t != null) { 33 | System.out.println("Cause: " + t); 34 | t = t.getCause(); 35 | } 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/h2/crud/H2SelectExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.h2.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | 8 | /** 9 | * Select PreparedStatement JDBC Example 10 | * 11 | * @author Ramesh Fadatare 12 | * 13 | */ 14 | public class H2SelectExample { 15 | private static final String QUERY = "select id,name,email,country,password from users where id =?"; 16 | 17 | public static void main(String[] args) { 18 | 19 | // using try-with-resources to avoid closing resources (boiler plate code) 20 | 21 | // Step 1: Establishing a Connection 22 | try (Connection connection = H2JDBCUtils.getConnection(); 23 | 24 | // Step 2:Create a statement using connection object 25 | PreparedStatement preparedStatement = connection.prepareStatement(QUERY);) { 26 | preparedStatement.setInt(1, 1); 27 | System.out.println(preparedStatement); 28 | // Step 3: Execute the query or update query 29 | ResultSet rs = preparedStatement.executeQuery(); 30 | 31 | // Step 4: Process the ResultSet object. 32 | while (rs.next()) { 33 | int id = rs.getInt("id"); 34 | String name = rs.getString("name"); 35 | String email = rs.getString("email"); 36 | String country = rs.getString("country"); 37 | String password = rs.getString("password"); 38 | System.out.println(id + "," + name + "," + email + "," + country + "," + password); 39 | } 40 | } catch (SQLException e) { 41 | H2JDBCUtils.printSQLException(e); 42 | } 43 | // Step 4: try-with-resource statement will auto close the connection. 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/h2/crud/H2UpdateExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.h2.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.PreparedStatement; 6 | import java.sql.SQLException; 7 | 8 | /** 9 | * Update PreparedStatement JDBC Example 10 | * @author Ramesh Fadatare 11 | * 12 | */ 13 | public class H2UpdateExample { 14 | 15 | private static final String UPDATE_USERS_SQL = "update users set name = ? where id = ?;"; 16 | 17 | public static void main(String[] argv) throws SQLException { 18 | H2UpdateExample updateStatementExample = new H2UpdateExample(); 19 | updateStatementExample.updateRecord(); 20 | } 21 | 22 | public void updateRecord() throws SQLException { 23 | System.out.println(UPDATE_USERS_SQL); 24 | // Step 1: Establishing a Connection 25 | try (Connection connection = H2JDBCUtils.getConnection(); 26 | // Step 2:Create a statement using connection object 27 | PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USERS_SQL)) { 28 | preparedStatement.setString(1, "Ram"); 29 | preparedStatement.setInt(2, 1); 30 | 31 | // Step 3: Execute the query or update query 32 | preparedStatement.executeUpdate(); 33 | } catch (SQLException e) { 34 | 35 | // print SQL exception information 36 | H2JDBCUtils.printSQLException(e); 37 | } 38 | 39 | // Step 4: try-with-resource statement will auto close the connection. 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/hsqldb/crud/HSQLDBCreateExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.hsqldb.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.SQLException; 5 | import java.sql.Statement; 6 | 7 | /** 8 | * Create Statement JDBC Example 9 | * @author Ramesh Fadatare 10 | * 11 | */ 12 | public class HSQLDBCreateExample { 13 | 14 | private static final String createTableSQL = "create table users (\r\n" + " id int(3) primary key,\r\n" + 15 | " name varchar(20),\r\n" + " email varchar(20),\r\n" + " country varchar(20),\r\n" + 16 | " password varchar(20)\r\n" + " );"; 17 | 18 | public static void main(String[] argv) throws SQLException { 19 | HSQLDBCreateExample createTableExample = new HSQLDBCreateExample(); 20 | createTableExample.createTable(); 21 | } 22 | 23 | public void createTable() throws SQLException { 24 | 25 | System.out.println(createTableSQL); 26 | // Step 1: Establishing a Connection 27 | try (Connection connection = JDBCUtils.getConnection(); 28 | // Step 2:Create a statement using connection object 29 | Statement statement = connection.createStatement();) { 30 | 31 | // Step 3: Execute the query or update query 32 | statement.execute(createTableSQL); 33 | } catch (SQLException e) { 34 | // print SQL exception information 35 | JDBCUtils.printSQLException(e); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/hsqldb/crud/HSQLDBDeleteExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.hsqldb.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.SQLException; 5 | import java.sql.Statement; 6 | 7 | public class HSQLDBDeleteExample { 8 | private static final String deleteTableSQL = "delete from users where id = 1"; 9 | 10 | public static void main(String[] argv) throws SQLException { 11 | HSQLDBDeleteExample deleteExample = new HSQLDBDeleteExample(); 12 | deleteExample.deleteRecord(); 13 | } 14 | 15 | public void deleteRecord() throws SQLException { 16 | 17 | System.out.println(deleteTableSQL); 18 | // Step 1: Establishing a Connection 19 | try (Connection connection = JDBCUtils.getConnection(); 20 | // Step 2:Create a statement using connection object 21 | Statement statement = connection.createStatement();) { 22 | 23 | // Step 3: Execute the query or update query 24 | statement.execute(deleteTableSQL); 25 | 26 | } catch (SQLException e) { 27 | // print SQL exception information 28 | JDBCUtils.printSQLException(e); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/hsqldb/crud/HSQLDBInsertExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.hsqldb.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.SQLException; 6 | 7 | /** 8 | * Insert PrepareStatement JDBC Example 9 | * 10 | * @author Ramesh Fadatare 11 | * 12 | */ 13 | public class HSQLDBInsertExample { 14 | private static final String INSERT_USERS_SQL = "INSERT INTO users" + 15 | " (id, name, email, country, password) VALUES " + 16 | " (?, ?, ?, ?, ?);"; 17 | 18 | public static void main(String[] argv) throws SQLException { 19 | HSQLDBInsertExample createTableExample = new HSQLDBInsertExample(); 20 | createTableExample.insertRecord(); 21 | } 22 | 23 | public void insertRecord() throws SQLException { 24 | System.out.println(INSERT_USERS_SQL); 25 | // Step 1: Establishing a Connection 26 | try (Connection connection = JDBCUtils.getConnection(); 27 | // Step 2:Create a statement using connection object 28 | PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) { 29 | preparedStatement.setInt(1, 1); 30 | preparedStatement.setString(2, "Tony"); 31 | preparedStatement.setString(3, "tony@gmail.com"); 32 | preparedStatement.setString(4, "US"); 33 | preparedStatement.setString(5, "secret"); 34 | 35 | System.out.println(preparedStatement); 36 | // Step 3: Execute the query or update query 37 | preparedStatement.executeUpdate(); 38 | } catch (SQLException e) { 39 | 40 | // print SQL exception information 41 | JDBCUtils.printSQLException(e); 42 | } 43 | 44 | // Step 4: try-with-resource statement will auto close the connection. 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/hsqldb/crud/HSQLDBSelectExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.hsqldb.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | 8 | /** 9 | * Select PreparedStatement JDBC Example 10 | * 11 | * @author Ramesh Fadatare 12 | * 13 | */ 14 | public class HSQLDBSelectExample { 15 | private static final String QUERY = "select id,name,email,country,password from users where id =?"; 16 | 17 | public static void main(String[] args) { 18 | 19 | // using try-with-resources to avoid closing resources (boiler plate code) 20 | 21 | // Step 1: Establishing a Connection 22 | try (Connection connection = JDBCUtils.getConnection(); 23 | 24 | // Step 2:Create a statement using connection object 25 | PreparedStatement preparedStatement = connection.prepareStatement(QUERY);) { 26 | preparedStatement.setInt(1, 1); 27 | System.out.println(preparedStatement); 28 | // Step 3: Execute the query or update query 29 | ResultSet rs = preparedStatement.executeQuery(); 30 | 31 | // Step 4: Process the ResultSet object. 32 | while (rs.next()) { 33 | int id = rs.getInt("id"); 34 | String name = rs.getString("name"); 35 | String email = rs.getString("email"); 36 | String country = rs.getString("country"); 37 | String password = rs.getString("password"); 38 | System.out.println(id + "," + name + "," + email + "," + country + "," + password); 39 | } 40 | } catch (SQLException e) { 41 | JDBCUtils.printSQLException(e); 42 | } 43 | // Step 4: try-with-resource statement will auto close the connection. 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/hsqldb/crud/HSQLDBUpdateExample.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.hsqldb.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.PreparedStatement; 6 | import java.sql.SQLException; 7 | 8 | /** 9 | * Update PreparedStatement JDBC Example 10 | * @author Ramesh Fadatare 11 | * 12 | */ 13 | public class HSQLDBUpdateExample { 14 | 15 | private static final String UPDATE_USERS_SQL = "update users set name = ? where id = ?;"; 16 | 17 | public static void main(String[] argv) throws SQLException { 18 | HSQLDBUpdateExample updateStatementExample = new HSQLDBUpdateExample(); 19 | updateStatementExample.updateRecord(); 20 | } 21 | 22 | public void updateRecord() throws SQLException { 23 | System.out.println(UPDATE_USERS_SQL); 24 | // Step 1: Establishing a Connection 25 | try (Connection connection = JDBCUtils.getConnection(); 26 | // Step 2:Create a statement using connection object 27 | PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USERS_SQL)) { 28 | preparedStatement.setString(1, "Ram"); 29 | preparedStatement.setInt(2, 1); 30 | 31 | // Step 3: Execute the query or update query 32 | preparedStatement.executeUpdate(); 33 | } catch (SQLException e) { 34 | 35 | // print SQL exception information 36 | JDBCUtils.printSQLException(e); 37 | } 38 | 39 | // Step 4: try-with-resource statement will auto close the connection. 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/net/javaguides/jdbc/hsqldb/crud/JDBCUtils.java: -------------------------------------------------------------------------------- 1 | package net.javaguides.jdbc.hsqldb.crud; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | 7 | public class JDBCUtils { 8 | 9 | private static String jdbcURL = "jdbc:hsqldb:hsql://localhost/testdb"; 10 | private static String jdbcUsername = "SA"; 11 | private static String jdbcPassword = ""; 12 | 13 | public static Connection getConnection() { 14 | Connection connection = null; 15 | try { 16 | connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword); 17 | } catch (SQLException e) { 18 | // TODO Auto-generated catch block 19 | e.printStackTrace(); 20 | } 21 | return connection; 22 | } 23 | 24 | public static void printSQLException(SQLException ex) { 25 | for (Throwable e : ex) { 26 | if (e instanceof SQLException) { 27 | e.printStackTrace(System.err); 28 | System.err.println("SQLState: " + ((SQLException) e).getSQLState()); 29 | System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); 30 | System.err.println("Message: " + e.getMessage()); 31 | Throwable t = ex.getCause(); 32 | while (t != null) { 33 | System.out.println("Cause: " + t); 34 | t = t.getCause(); 35 | } 36 | } 37 | } 38 | } 39 | } 40 | --------------------------------------------------------------------------------