Addition, deletion, modification and checking of JDBC basic learning (3)

1. Preparatory work, create the table personnel information table (t_person), user table (user), organization information table (t_org)

sql script:

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50162
Source Host           : localhost:3306
Source Database       : demo

Target Server Type    : MYSQL
Target Server Version : 50162
File Encoding         : 65001

Date: 2017-12-02 10:07:32
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for t_org
-- ----------------------------
DROP TABLE IF EXISTS `t_org`;
CREATE TABLE `t_org` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `pid` int(4) DEFAULT NULL,
  `name` varchar(100) NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_org
-- ----------------------------
INSERT INTO `t_org` VALUES ('1', '0', 'implementation group', 'investigation, implementation');
INSERT INTO `t_org` VALUES ('2', '0', 'development group', 'development');
INSERT INTO `t_org` VALUES ('3', '0', 'Finance Department', 'Accounting,');
INSERT INTO `t_org` VALUES ('4', '0', 'Human Resources', 'Human Resources');

-- ----------------------------
-- Table structure for t_person
-- ----------------------------
DROP TABLE IF EXISTS `t_person`;
CREATE TABLE `t_person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `oid` int(4) DEFAULT NULL,
  `name` varchar(100) NOT NULL,
  `sex` char(1) NOT NULL,
  `address` varchar(200) DEFAULT NULL,
  `age` int(4) DEFAULT NULL,
  `phone` varchar(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_person
-- ----------------------------
INSERT INTO `t_person` VALUES ('1', '1', 'Zhang San', '1', 'xxxxx', '20', '13984848326');
INSERT INTO `t_person` VALUES ('2', '1', 'Zhang Fei', '1', 'xxxxx', '22', '10086');
INSERT INTO `t_person` VALUES ('3', '2', 'Yang Guo', '1', 'xxxxx', '25', '10000');
INSERT INTO `t_person` VALUES ('4', '3', 'Little Dragon Girl', '0', 'xxxxx', '25', '10086');

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(4) NOT NULL,
  `pid` int(11) DEFAULT NULL,
  `user_name` varchar(50) NOT NULL,
  `password` varchar(50) DEFAULT NULL,
  `create_time` bigint(20) DEFAULT NULL,
  `expired_time` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '1', 'zhangsan', '123456', null, null);
INSERT INTO `user` VALUES ('2', '2', 'zhangfei', '123456', null, null);
INSERT INTO `user` VALUES ('3', '3', 'yangguo', '123456', null, null);
INSERT INTO `user` VALUES ('4', '4', 'xiaolongnv', '123456', null, null);

 2. Query all the information in the personnel table

public class Test {

	public static void main(String[] args) {
		Connection conn = null;
		String url = "jdbc:mysql://127.0.0.1:3306/demo";
		String user = "root";
		String password = "root_123";
		ResultSet rs = null;
		Statement stmt = null;
		try {
			// Step 1: Load the driver
			Class.forName("com.mysql.jdbc.Driver");
			// Step 2: Get the link
			conn = DriverManager.getConnection(url, user, password);
			//Step 3: Create a statement that executes the SQL statement
			stmt = conn.createStatement();
			String sql = "select * from t_person";
			//Step 4: Process the result of execution
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				StringBuffer sb = new StringBuffer();
				sb.append("id:" + rs.getInt("id") + "\t")
				  .append("name:" + rs.getString("name")  + "\t")
				  .append("address:" + rs.getString("address")  + "\t")
				  .append("sex:" + rs.getString("sex")  + "\t")
				  .append("age:" + rs.getInt("age")  + "\t")
				  .append("phone:" + rs.getString("phone")  + "\t");
				System.out.println(sb.toString());
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace ();
		} catch (SQLException e) {
			e.printStackTrace ();
		}finally{
			//Step 5: Release resources
			if(null != rs){
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace ();
				}
			}
			if(null != stmt){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace ();
				}
			}
			if(null != conn){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace ();
				}
			}
		}
	}

}

3. Create table t_test

 

public class Test2 {

	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		String url = "jdbc:mysql://127.0.0.1:3306/demo";
		String user = "root";
		String password = "root_123";
		try {
			//The first step: load the driver
			Class.forName("com.mysql.jdbc.Driver");
			//Step 2: Get the link
			conn = DriverManager.getConnection(url, user, password);
			//Step 3: Create a statement that executes SQL
			stmt = conn.createStatement();
			StringBuffer sbSql = new StringBuffer();
			sbSql.append("create table t_test( ")
				 .append("id int(4) primary key not null, ")
				 .append("user_name varchar (20) not null ")
				 .append(");");
			stmt.executeUpdate(sbSql.toString());
		} catch (ClassNotFoundException e) {
			e.printStackTrace ();
		} catch (SQLException e) {
			e.printStackTrace ();
		}finally{
			//Step 4: Release resources
			if(null != stmt){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace ();
				}
			}
			if(null != conn){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace ();
				}
			}
		}
	}
}

 Thinking: Infer other things from one case, you can try to delete, modify and other operations.

Fourth, the tool class DBUtil to connect to the database

 

Since the common operation on the database is CRUD , and the basic steps are similar, we encapsulate the connection of the database and the closing of the resource .

 

package com.zlt.jdbc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Encapsulate database connection and resource release into a common tool class
 *
 * @author Tao Shengyi laughs 289836653
 *
 */
public class DBUtil {

	/**
	 * get database connection
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		String url = "jdbc:mysql://127.0.0.1:3306/demo";
		String user = "root";
		String password = "root_123";
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace ();
		} catch (SQLException e) {
			e.printStackTrace ();
		}
		return conn;
	}

	/**
	 * Release the result set resource
	 * @param lol
	 */
	public static void close(ResultSet rs){
		if(null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace ();
			}
		}
	}
	
	/**
	 * Release statement resources for executing SQL
	 * @param stmt
	 */
	public static void close(Statement stmt){
		if(null != stmt) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace ();
			}
	}
	
	
	/**
	 * Release the database connection Connection
	 * @param conn
	 */
	public static void close(Connection conn){
		if(null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace ();
			}
		}
	}
}

 unit test

package com.zlt.jdbc.util;

import junit.framework.TestCase;

public class DBUtilTest extends TestCase {
	protected void setUp() throws Exception {
		super.setUp();
	}
	public void testGetConnection() {
		System.out.println(DBUtil.getConnection());
	}
}

 5. Link the results of the query with the JAVA object model

        5.1 Establishing an Object Model (JavaBean)

package com.zlt.jdbc;

/**
 * Establish the mapping between the relational model and the object model
 * Object model entity Person and relational model t_person (for the time being, the association between relationships and relationships is not considered)
 * @author Tao Shengyi laughs 289836653
 *
 */
public class Person {
	
	private int id;
	private int oid;
	private String name;
	private String sex;
	private String address;
	private int age;
	private String phone;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getOid() {
		return oid;
	}
	public void setOid(int oid) {
		this.oid = oid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}		
}

 

    5.2 Query personnel information based on personnel ID

package com.zlt.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.zlt.jdbc.util.DBUtil;

public class Test3 {

	public static void main(String[] args) {
		Person p = findPersonById(1);
		System.out.println("id:" + p.getId() +"name:" +p.getName() + "age:" + p.getAge() + "sex:" + p.getSex() + "oid:" + p.getOid() + "address:" + p.getAddress() +"phone:" + p.getPhone());
	}
	
	/**
	 * Query the information of the person based on the person ID
	 * (It is recommended to tune the SQL statement first when writing code at ordinary times)
	 * select id,oid,name,sex,age,address,phone from t_person
	 * @param id Person ID
	 * @return p, when p is null, it means no query
	 */
	public static Person findPersonById(int id){
		Person p = null;
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn  = DBUtil.getConnection();
			stmt = conn.createStatement();
			String sql = "select id,oid,name,sex,age,address,phone from t_person";
			rs = stmt.executeQuery(sql);
			if(rs.next()) {
				p = new Person();
				p.setId(rs.getInt("id"));
				p.setName(rs.getString("name"));
				p.setOid(rs.getInt("oid"));
				p.setSex(rs.getString("sex"));
				p.setAge(rs.getInt("age"));
				p.setAddress(rs.getString("address"));
				p.setPhone(rs.getString("phone"));
			}
		} catch (SQLException e) {
			e.printStackTrace ();
		}finally{
			DBUtil.close(stmt);
			DBUtil.close(rs);
			DBUtil.close(conn);
		}
		return p;
	}
}

    5.3 Query the information of the person named Zhang

public static List<Person> findPersonByName(String name){
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		List<Person> persons = new ArrayList<Person>();
		try {
			conn  = DBUtil.getConnection();
			stmt = conn.createStatement();
			String sql = "select id,oid,name,sex,age,address,phone from t_person where name like '%"+name+"%'";
			rs = stmt.executeQuery(sql);
			while(rs.next()) {
				Person p = new Person();
				p.setId(rs.getInt("id"));
				p.setName(rs.getString("name"));
				p.setOid(rs.getInt("oid"));
				p.setSex(rs.getString("sex"));
				p.setAge(rs.getInt("age"));
				p.setAddress(rs.getString("address"));
				p.setPhone(rs.getString("phone"));
				persons.add(p);
			}
		} catch (SQLException e) {
			e.printStackTrace ();
		}finally{
			DBUtil.close(stmt);
			DBUtil.close(rs);
			DBUtil.close(conn);
		}
		return persons;
	}

    5.4 Remaining problems: At this time, when using Statement to execute SQL statements, there are two disadvantages. 1) There is a problem of SQL injection. 2) The more control conditions, the more complicated the difficulty of stringing together.

wrote
It is recommended to use the PreparedStatement statement, which effectively prevents sql injection (the SQL statement has been precompiled before the program runs, and when the parameter is dynamically passed to the PreprareStatement at runtime, even if there are sensitive characters in the parameter such as or '1=1', The database will process the property value of a field as a parameter and not as an SQL command

    5.5 Use the PrepareStatement statement to rewrite the b example, but when rewriting the c example, it is found that the fuzzy query can not find the result but the program is correct, so it is generally recommended to use PrepareStatement, but sometimes you must use Statement to string together

public static Person findPersonById(int id){
		Person p = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn  = DBUtil.getConnection();
			String sql = "select id,oid,name,sex,age,address,phone from t_person where id = ?" ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
			rs = pstmt.executeQuery();
			if(rs.next()) {
				p = new Person();
				p.setId(rs.getInt("id"));
				p.setName(rs.getString("name"));
				p.setOid(rs.getInt("oid"));
				p.setSex(rs.getString("sex"));
				p.setAge(rs.getInt("age"));
				p.setAddress(rs.getString("address"));
				p.setPhone(rs.getString("phone"));
			}
		} catch (SQLException e) {
			e.printStackTrace ();
		}finally{
			DBUtil.close(pstmt);
			DBUtil.close(rs);
			DBUtil.close(conn);
		}
		return p;
	}

   learn by analogy:

wrote
1) Query the information of personnel whose personnel numbers are 1, 3, and 5.
2) Query the information of people between the ages of 20-25
3) Update the address and phone number of the person named Xiaolongnu to the bottom of the heartless valley, 10008611
4) Insert a new person (5,3, Zhou Botong, 1, 30, Cosmopolitan, 10086)
5) Delete Zhang San and Zhang Fei from the table
6) Query the user information and personnel information named Yang Guo

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326260955&siteId=291194637