PreparedStatement in JDBC

Using Statement requires spelling SQL statements, which is cumbersome and error-prone, which uses PreparedStatement. PreparedStatement is a sub-interface of Statement, which can pass in SQL statements with placeholders and provides methods to supplement placeholder variables.

1. Use PreparedStatement

1.1 Create PreparedStatement;

String sql="INSERT INTO EXAMSTUDENT VALUES(?,?,?,?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);

1.2 Use setXxx (int index, Object val) of PreparedStatement to set the placeholder value;

1.3 Execute SQL statement: executeQuery () or executeUpdate (). Note: SQL statements are no longer required during execution.

 Sample code:

@Test
public void testPreparedStatement(){
	Connection connection=null;
	PreparedStatement preparedstatement=null;
	
	try{
		String sql="INSERT INTO EXAMSTUDENT VALUES(?,?,?,?,?,?,?)";
		connection=JDBCTools.getConnection();
		preparedstatement=connection.prepareStatement(sql);
		preparedstatement.setInt(1, 3);
		preparedstatement.setInt(2, 434);
		preparedstatement.setString(3, "198312");
		preparedstatement.setString(4, "342");
		preparedstatement.setString(5, "Peter");
		preparedstatement.setString(6, "上海");
		preparedstatement.setInt(7, 332);
		preparedstatement.executeUpdate();
	}catch(Exception e){
		e.printStackTrace();
		}finally{
			JDBCTools.release(preparedstatement,connection);
		}
}

2. Use PreparedStatement to add student information to the data table

Student.java

package com.test.jdbc;

public class Student {
	private int flowId;
	private int type;
	private String idCard;
	private String examCard;
	private String studentName;
	private String location;
	private int grade;
	public int getFlowId() {
		return flowId;
	}
	public void setFlowId(int flowId) {
		this.flowId = flowId;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	public String getIdCard() {
		return idCard;
	}
	public void setIdCard(String idCard) {
		this.idCard = idCard;
	}
	public String getExamCard() {
		return examCard;
	}
	public void setExamCard(String examCard) {
		this.examCard = examCard;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
	public Student(int flowId, int type, String idCard, String examCard, String studentName, String location,
			int grade) {
		super();
		this.flowId = flowId;
		this.type = type;
		this.idCard = idCard;
		this.examCard = examCard;
		this.studentName = studentName;
		this.location = location;
		this.grade = grade;
	}
	public Student(){ }
	@Override
	public String toString() {
		return "student [flowId=" + flowId + ", type=" + type + ", idCard=" + idCard + ", examCard=" + examCard
				+ ", studentName=" + studentName + ", location=" + location + ", grade=" + grade + "]";
	}
	
}

Tool class JDBCTools.java

package com.test.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.junit.Test;

public class JDBCTools {
	//添加数据并更新
	public static void update2(String sql,Object...args){
		Connection connection=null;
		PreparedStatement preparedstatement=null;
		try{
			connection=JDBCTools.getConnection();
			preparedstatement=connection.prepareStatement(sql);
			for(int i=0;i<args.length;i++){
				preparedstatement.setObject(i+1,args[i]);
			}
			preparedstatement.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCTools.release(preparedstatement, connection);
		}
	}
	
	//获取数据库的连接
	public static Connection getConnection() throws Exception{
		String driverClass=null;
		String jdbcUrl=null;
		String user=null;
		String password=null;
		
		InputStream in=JDBCTools.class.getResourceAsStream("/jdbc.properties");
		Properties properties=new Properties();
		properties.load(in);
		
		driverClass=properties.getProperty("driver");
		jdbcUrl=properties.getProperty("jdbcUrl");
		user=properties.getProperty("user");
		password=properties.getProperty("password");
		
		Class.forName(driverClass);
		Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
		
		return connection;
	}
    @Test 
    public void testGetConnection() throws Exception{
    	getConnection();
    }
	//数据库释放
    public static void release(Statement statement,Connection connection){
        if(statement!=null){
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        }
        if(connection!=null){
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    }
}

Function implementation class: JDBCTest.java

package com.test.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import org.junit.Test;

public class JDBCTest {
	@Test
	public void testAddNewStudent2(){
		Student student=getStudentFromConsole();
		addNewStudent2(student);
	}
	//从控制台输入学生的信息
	private Student getStudentFromConsole() {
		Scanner scanner=new Scanner(System.in);
		Student student=new Student();
		System.out.print("FlowId:");
		student.setFlowId(scanner.nextInt());
		System.out.print("Type:");
		student.setType(scanner.nextInt());
		System.out.print("IDCard:");
		student.setIdCard(scanner.next());
		System.out.print("ExamCard:");
		student.setExamCard(scanner.next());
		System.out.print("StudentName:");
		student.setStudentName(scanner.next());
		System.out.print("Location:");
		student.setLocation(scanner.next());
		System.out.print("Grade:");
		student.setGrade(scanner.nextInt());
		return student;
	}
	public void addNewStudent2(Student student){
		String sql="INSERT INTO EXAMSTUDENT VALUES(?,?,?,?,?,?,?)";
		JDBCTools.update2(sql, student.getFlowId(),student.getType(),student.getIdCard(),
				student.getExamCard(),student.getStudentName(),student.getLocation(),student.getGrade());
	}
}

 

wx search for "programmer koala", focus on the field of java, a public number that grows with you!

Published 13 original articles · Likes2 · Visits 568

Guess you like

Origin blog.csdn.net/weixin_40273144/article/details/105660428