1. 程式人生 > >dljd_016_jdbc中使用PreparedStatement執行DQL(查詢)語句

dljd_016_jdbc中使用PreparedStatement執行DQL(查詢)語句

一、jdbc使用preparedStatement執行dql(查詢)語句示例

  

package edu.aeon.jdbc.crud;

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

import edu.aeon.aeonutils.AeonJdbcUtils;
/**
 * [說明]:使用jdbc進行資料操作
 * @author aeon
 */
public class
JDBC_insert { /** * 使用jdbc進行增加操作(DML) */ public static void jdbc_insert(){ Connection connection=null; PreparedStatement preparedStatement = null; try { connection = AeonJdbcUtils.getMySqlConnection(); String sql="insert into user(userid,username,userpw) values (?,?,?)";
//將sql語句進行預編譯然後儲存到preparedStatement物件中 preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, 10006); preparedStatement.setString(2, "aeon"); preparedStatement.setString(3, "aeon"); int rowCount = preparedStatement.executeUpdate(); System.out.println(rowCount
+"條資料被插入!"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { AeonJdbcUtils.closeDB(null, preparedStatement, connection); } } /** * 查詢操作(DQL) * @param args */ public static void jdbc_select(){ Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection=AeonJdbcUtils.getMySqlConnection(); String sql="select userid,username,userpw from user where userid > ?"; preparedStatement=connection.prepareStatement(sql); preparedStatement.setInt(1, 10002); resultSet = preparedStatement.executeQuery(); System.out.println("使用者id\t使用者名稱\t使用者密碼"); while(resultSet.next()){ int userid=resultSet.getInt("userid"); String username=resultSet.getString("username"); String userpw=resultSet.getString("userpw"); System.out.println(userid+"\t"+username+"\t"+userpw); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally{ AeonJdbcUtils.closeDB(resultSet, preparedStatement, connection); } } public static void main(String[] args) { //jdbc_insert(); jdbc_select(); } }

資料庫截圖:

  

 

執行結果截圖: