Yam Code
Sign up
Login
New paste
Home
Trending
Archive
English
English
Tiếng Việt
भारत
Sign up
Login
New Paste
Browse
package net.javaguides.usermanagement.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import net.javaguides.usermanagement.model.User; /** * * AbstractDAO.java This DAO class provides CRUD database operations for the * * table users in the database. * * @author Ramesh Fadatare * */ public class UserDAO { private String jdbcURL = "jdbc:mysql://localhost:3306/demo?useSSL=false"; private String jdbcUsername = "root"; private String jdbcPassword = "root"; private static final String INSERT_USERS_SQL = "INSERT INTO users" + " (name, email, country) VALUES " + " (?, ?, ?);"; private static final String SELECT_USER_BY_ID = "select id,name,email,country from users where id =?"; private static final String SELECT_ALL_USERS = "select * from users"; private static final String DELETE_USERS_SQL = "delete from users where id = ?;"; private static final String UPDATE_USERS_SQL = "update users set name = ?,email= ?, country =? where id = ?;"; public UserDAO() { } protected Connection getConnection() { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } public void insertUser(User user) throws SQLException { System.out.println(INSERT_USERS_SQL); // try-with-resource statement will auto close the connection. try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) { preparedStatement.setString(1, user.getName()); preparedStatement.setString(2, user.getEmail()); preparedStatement.setString(3, user.getCountry()); System.out.println(preparedStatement); preparedStatement.executeUpdate(); } catch (SQLException e) { printSQLException(e); } } public User selectUser(int id) { User user = null; // Step 1: Establishing a Connection try (Connection connection = getConnection(); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USER_BY_ID);) { preparedStatement.setInt(1, id); System.out.println(preparedStatement); // Step 3: Execute the query or update query ResultSet rs = preparedStatement.executeQuery(); // Step 4: Process the ResultSet object. while (rs.next()) { String name = rs.getString("name"); String email = rs.getString("email"); String country = rs.getString("country"); user = new User(id, name, email, country); } } catch (SQLException e) { printSQLException(e); } return user; } public List<User> selectAllUsers() { // using try-with-resources to avoid closing resources (boiler plate code) List<User> users = new ArrayList<>(); // Step 1: Establishing a Connection try (Connection connection = getConnection(); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS);) { System.out.println(preparedStatement); // Step 3: Execute the query or update query ResultSet rs = preparedStatement.executeQuery(); // Step 4: Process the ResultSet object. while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); String country = rs.getString("country"); users.add(new User(id, name, email, country)); } } catch (SQLException e) { printSQLException(e); } return users; } public boolean deleteUser(int id) throws SQLException { boolean rowDeleted; try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(DELETE_USERS_SQL);) { statement.setInt(1, id); rowDeleted = statement.executeUpdate() > 0; } return rowDeleted; } public boolean updateUser(User user) throws SQLException { boolean rowUpdated; try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(UPDATE_USERS_SQL);) { statement.setString(1, user.getName()); statement.setString(2, user.getEmail()); statement.setString(3, user.getCountry()); statement.setInt(4, user.getId()); rowUpdated = statement.executeUpdate() > 0; } return rowUpdated; } private void printSQLException(SQLException ex) { for (Throwable e : ex) { if (e instanceof SQLException) { e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) { System.out.println("Cause: " + t); t = t.getCause(); } } } } }
Paste Settings
Paste Title :
[Optional]
Paste Folder :
[Optional]
Select
Syntax Highlighting :
[Optional]
Select
Markup
CSS
JavaScript
Bash
C
C#
C++
Java
JSON
Lua
Plaintext
C-like
ABAP
ActionScript
Ada
Apache Configuration
APL
AppleScript
Arduino
ARFF
AsciiDoc
6502 Assembly
ASP.NET (C#)
AutoHotKey
AutoIt
Basic
Batch
Bison
Brainfuck
Bro
CoffeeScript
Clojure
Crystal
Content-Security-Policy
CSS Extras
D
Dart
Diff
Django/Jinja2
Docker
Eiffel
Elixir
Elm
ERB
Erlang
F#
Flow
Fortran
GEDCOM
Gherkin
Git
GLSL
GameMaker Language
Go
GraphQL
Groovy
Haml
Handlebars
Haskell
Haxe
HTTP
HTTP Public-Key-Pins
HTTP Strict-Transport-Security
IchigoJam
Icon
Inform 7
INI
IO
J
Jolie
Julia
Keyman
Kotlin
LaTeX
Less
Liquid
Lisp
LiveScript
LOLCODE
Makefile
Markdown
Markup templating
MATLAB
MEL
Mizar
Monkey
N4JS
NASM
nginx
Nim
Nix
NSIS
Objective-C
OCaml
OpenCL
Oz
PARI/GP
Parser
Pascal
Perl
PHP
PHP Extras
PL/SQL
PowerShell
Processing
Prolog
.properties
Protocol Buffers
Pug
Puppet
Pure
Python
Q (kdb+ database)
Qore
R
React JSX
React TSX
Ren'py
Reason
reST (reStructuredText)
Rip
Roboconf
Ruby
Rust
SAS
Sass (Sass)
Sass (Scss)
Scala
Scheme
Smalltalk
Smarty
SQL
Soy (Closure Template)
Stylus
Swift
TAP
Tcl
Textile
Template Toolkit 2
Twig
TypeScript
VB.Net
Velocity
Verilog
VHDL
vim
Visual Basic
WebAssembly
Wiki markup
Xeora
Xojo (REALbasic)
XQuery
YAML
HTML
Paste Expiration :
[Optional]
Never
Self Destroy
10 Minutes
1 Hour
1 Day
1 Week
2 Weeks
1 Month
6 Months
1 Year
Paste Status :
[Optional]
Public
Unlisted
Private (members only)
Password :
[Optional]
Description:
[Optional]
Tags:
[Optional]
Encrypt Paste
(
?
)
Create New Paste
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login
Site Languages
×
English
Tiếng Việt
भारत