1. 程式人生 > >PerparedStatement的使用,及模糊查詢時候的引數注入

PerparedStatement的使用,及模糊查詢時候的引數注入

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

public class PreparStatementTest2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		String url = "jdbc:mysql://localhost:3306/mysqletc";
		String user = "root";
		String password = "123456";
		// 載入驅動
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// 得到連線
			Connection conn = DriverManager.getConnection(url, user, password);
			// 建立PerparedStatement
			//String sql = "select * from commodity where name like '%?%'";
			String search = "米";
			String sql = "select * from commodity where name like ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			search = "%"+search+"%";
			ps.setString(1, search);
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				System.out.println(rs.getInt("id")+rs.getString("name"));
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			
		}
	}

}