In-depth analysis of JavaWeb Item28 -- use JDBC to perform CRUD on the database

Source: Internet
Author: User

In-depth analysis of JavaWeb Item28 -- use JDBC to perform CRUD on the database
1. Introduction to statement objects

The statement object in Jdbc is used to send SQL statements to the database. to add, delete, modify, and query the database, you only need to send the add, delete, modify, and query statements to the database through this object.
Statement objectexecuteUpdateMethod, used to send SQL statements for adding, deleting, and modifying to the database. After executeUpdate is executed, an integer is returned (that is, the number of rows of data in the database has changed due to the addition, deletion, and modification of statements ).
The Statement.exe cuteQuery method is used to send query statements to the database. The executeQuery method returns the ResultSet object representing the query result.

1.1. CRUD operation-create

Use the executeUpdate (String SQL) method to add data. Example operations:

Statement st = conn. createStatement (); String SQL = "insert into user (....) Values (.....) "; Int num = st.exe cuteUpdate (SQL); if (num> 0) {System. out. println (" inserted successfully !!! ");}
1.2. CRUD operation-update

Use the executeUpdate (String SQL) method to modify data. Example operations:

Statement st = conn. createStatement (); String SQL = "update user set name = ''where name ='' "; int num = st.exe cuteUpdate (SQL); if (num> 0) {System. out. println ("modification successful !!! ");}
1.3. CRUD operation-delete

Use the executeUpdate (String SQL) method to delete data. Example operations:

Statement st = conn. createStatement (); String SQL = "delete from user where id = 1; int num = st.exe cuteUpdate (SQL); if (num> 0) {System. out. println ("deleted successfully !!! ");}
1.4. CRUD operation-select

Use the executeQuery (String SQL) method to query data. Example operations:

Statement st = conn. createStatement (); String SQL = "select * from user where id = 1; ResultSet rs = st.exe cuteUpdate (SQL); while (rs. next () {// call the corresponding methods of rs to map to the java object based on the data type of the retrieved column}
2. add, delete, modify, and query databases using jdbc

2.1 build an experimental environment

1. Create a database in mysql, create a user table, and insert Table data.

The SQL script is as follows:

create database jdbcStudy;use jdbcStudy;create table users(    id int primary key,    name varchar(40),    password varchar(40),    email varchar(60),    birthday date);

2. Create a JavaWeb project and import the MySQL database driver.

  

3. Create a db. properties file in the src directory, as shown in:

  

Write the connection information of the MySQL database in db. properties. The Code is as follows:

 driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcStudy username=root password=XDP

4. Compile a JdbcUtils tool class to connect to the database, obtain the database connection and release the database connection. The Code is as follows:

Package me. gacl. utils; import java. io. inputStream; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; import java. util. properties; public class JdbcUtils {private static String driver = null; private static String url = null; private static String username = null; private static String password = null; static {try {// Read the database. the database connection information in the properties file is InputStream in = JdbcUtils. class. getClassLoader (). getResourceAsStream ("db. properties "); Properties prop = new Properties (); prop. load (in); // obtain the database connection driver = prop. getProperty ("driver"); // obtain the database connection URL url = prop. getProperty ("url"); // obtain the database connection username = prop. getProperty ("username"); // obtain the database connection password = prop. getProperty ("password"); // load the database Driver Class. forName (drive R);} catch (Exception e) {throw new ExceptionInInitializerError (e);}/*** @ Method: getConnection * @ Description: Get the database connection object * @ Anthor: gu AO Canglang ** @ return Connection database Connection object * @ throws SQLException */public static Connection getConnection () throws SQLException {return DriverManager. getConnection (url, username, password);}/*** @ Method: release * @ Description: releases the resource. * The resource to be released includes the Connection database Connection object and is responsible for executing The Statement object of the SQL command, which stores the ResultSet object of the query result * @ Anthor: gu AO Canglang ** @ param conn * @ param st * @ param rs */public static void release (Connection conn, Statement st, ResultSet rs) {if (rs! = Null) {try {// close the rs object that stores the query results. close ();} catch (Exception e) {e. printStackTrace ();} rs = null;} if (st! = Null) {try {// close the Statement object st. close ();} catch (Exception e) {e. printStackTrace () ;}} if (conn! = Null) {try {// close Connection database Connection object conn. close () ;}catch (Exception e) {e. printStackTrace ();}}}}
2.2 Use the statement object to perform CRUD operations on the database

The test code is as follows:

Package me. gacl. demo; import java. SQL. connection; import java. SQL. resultSet; import java. SQL. statement; import me. gacl. utils. jdbcUtils; import org. junit. test;/*** @ ClassName: JdbcCRUDByStatement * @ Description: Use the Statement object to perform CRUD operations on the database * @ author: lone wolf * @ date: 11:22:12 **/public class JdbcCRUDByStatement {@ Test public void insert () {Connection conn = null; Statement st = null; ResultSet rs = Null; try {// get a database connection conn = JdbcUtils. getConnection (); // use the conn object to obtain the Statement object st = conn. createStatement (); // The SQL command to be executed String SQL = "insert into users (id, name, password, email, birthday) values (3, 'white-nove ', '200', '[email protected]', '1970-09-09 ') "; // execute the insert operation. The number of successful results returned by the executeUpdate method int num = st.exe cuteUpdate (SQL ); if (num> 0) {System. out. println ("insert successful !! ") ;}} Catch (Exception e) {e. printStackTrace ();} finally {// Release related resources after SQL Execution is complete. release (conn, st, rs) ;}@ Test public void delete () {Connection conn = null; Statement st = null; ResultSet rs = null; try {conn = JdbcUtils. getConnection (); String SQL = "delete from users where id = 3"; st = conn. createStatement (); int num = st.exe cuteUpdate (SQL); if (num> 0) {System. out. println ("deleted successfully !! ") ;}} Catch (Exception e) {e. printStackTrace ();} finally {JdbcUtils. release (conn, st, rs) ;}@ Test public void update () {Connection conn = null; Statement st = null; ResultSet rs = null; try {conn = JdbcUtils. getConnection (); String SQL = "update users set name = 'lone wolf ', email =' [email protected] 'where id = 3"; st = conn. createStatement (); int num = st.exe cuteUpdate (SQL); if (num> 0) {System. out. print Ln ("Update successful !! ") ;}} Catch (Exception e) {e. printStackTrace ();} finally {JdbcUtils. release (conn, st, rs) ;}@ Test public void find () {Connection conn = null; Statement st = null; ResultSet rs = null; try {conn = JdbcUtils. getConnection (); String SQL = "select * from users where id = 3"; st = conn. createStatement (); rs = st.exe cuteQuery (SQL); if (rs. next () {System. out. println (rs. getString ("name") ;}} catch (Exception e) {e. printStackTrace ();} finally {JdbcUtils. release (conn, st, rs );}}}
Iii. Introduction to PreparedStatement objects

PreperedStatement is a subclass of Statement. Its instance object can be calledConnection.preparedStatement()Method. Compared with the Statement object, PreperedStatement can avoid the problem of SQL injection.
  
Statement can frequently compile SQL statements in the database and cause database Buffer Overflow. PreparedStatement can pre-compile SQL statements to improve the execution efficiency of the database. In addition, PreperedStatement allows replacement of parameters in SQL in the form of placeholders to simplify the preparation of SQL statements.

3.1 Use the PreparedStatement object to perform CRUD operations on the database

The test code is as follows:

Package me. gacl. demo; import java. SQL. connection; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. util. date; import me. gacl. utils. jdbcUtils; import org. junit. test;/*** @ ClassName: JdbcCRUDByPreparedStatement * @ Description: Use the PreparedStatement object to perform CRUD operations on the database * @ author: lone wolf * @ date: 11:21:42 **/public class JdbcCRUDByPreparedStatement {@ Test public void insert () {Conne Ction conn = null; PreparedStatement st = null; ResultSet rs = null; try {// get a database connection conn = JdbcUtils. getConnection (); // The SQL command to be executed. How can I use the SQL parameter? As the placeholder String SQL = "insert into users (id, name, password, email, birthday) values (?,?,?,?,?) "; // Get the prepareStatement object st = conn that executes SQL commands through the conn object. prepareStatement (SQL); // assign values to parameters in the SQL statement. Note that the index is from 1. the type of each field in the/*** SQL statement is as follows: * + ---------- + ------------- + | Field | Type | + ---------- + ------------- + | id | int (11) | name | varchar (40) | password | varchar (40) | email | varchar (60) | birthday | date | + ---------- + ----------- + */st. setInt (1, 1); // id is the st of the int type. setString (2, "White Tiger Emperor"); // The name is v Archar (string type) st. setString (3, "123"); // The password is varchar (string type) st. setString (4, "[email protected]"); // email is a varchar (string type) st. setDate (5, new java. SQL. date (new Date (). getTime (); // birthday is of the date type // execute the insert operation. The number of successful results returned by the executeUpdate method int num = st.exe cuteUpdate (); if (num> 0) {System. out. println ("insert successful !! ") ;}} Catch (Exception e) {e. printStackTrace ();} finally {// Release related resources after SQL Execution is complete. release (conn, st, rs) ;}@ Test public void delete () {Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try {conn = JdbcUtils. getConnection (); String SQL = "delete from users where id =? "; St = conn. prepareStatement (SQL); st. setInt (1, 1); int num = st.exe cuteUpdate (); if (num> 0) {System. out. println ("deleted successfully !! ") ;}} Catch (Exception e) {e. printStackTrace ();} finally {JdbcUtils. release (conn, st, rs) ;}@ Test public void update () {Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try {conn = JdbcUtils. getConnection (); String SQL = "update users set name = ?, Email =? Where id =? "; St = conn. prepareStatement (SQL); st. setString (1, "gacl"); st. setString (2, "[email protected]"); st. setInt (3, 2); int num = st.exe cuteUpdate (); if (num> 0) {System. out. println ("Update successful !! ") ;}} Catch (Exception e) {e. printStackTrace ();} finally {JdbcUtils. release (conn, st, rs) ;}@ Test public void find () {Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try {conn = JdbcUtils. getConnection (); String SQL = "select * from users where id =? "; St = conn. prepareStatement (SQL); st. setInt (1, 1); rs = st.exe cuteQuery (); if (rs. next () {System. out. println (rs. getString ("name") ;}} catch (Exception e) {} finally {JdbcUtils. release (conn, st, rs );}}}

The above is a brief summary of CRUD for databases using JDBC.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.