Java PreparedStatement用法詳解
PreparedStatement常用的方法:
void setObject(int parameterIndex, Object x, int targetSqlType)
parameterIndex the first parameter is 1, the second is 2, …占位符參數索引是從1開始的其余也是如此:
void setInt(int parameterIndex, int x)void setLong(int parameterIndex, long x)void setString(int parameterIndex, String x)void setBlob (int parameterIndex, Blob x)void setDate(int parameterIndex, java.sql.Date x, Calendar cal)
執行操作:
package com.atmf;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Properties;import org.junit.Test;public class SumUP {@Testpublic void getConnection() {Connection con = null;PreparedStatement ps = null;try {//1,加載配置文件InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream('jdbc.properties');Properties pr = new Properties();pr.load(is);//2,讀取配置信息String user = pr.getProperty('user');String password = pr.getProperty('password');String url = pr.getProperty('url');String driverClass = pr.getProperty('driverClass');//3.加載驅動Class.forName(driverClass);//4,獲取連接con = DriverManager.getConnection(url, user,password);String sql = 'insert into customers(name,birth) value(?,?)';//預編譯sql語句,得到PreparedStatement對象ps = con.prepareStatement(sql);//5,填充占位符ps.setString(1, '三明治');SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd');Date date = sdf.parse('2020-11-02');ps.setDate(2, new java.sql.Date(date.getTime()));//6,執行操作ps.execute();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {//7,關閉資源try {if(ps != null)ps.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}try {if(con != null)con.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
配置信息:jdbc.properties文件user=rootpassword=123456url=jdbc:mysql://localhost:3306/studentsdriverClass=com.mysql.jdbc.Driver
執行結果:
PreparedStatement實現對表數據的增刪改查操作
到此這篇關于Java PreparedStatement用法詳解的文章就介紹到這了,更多相關Java PreparedStatement用法內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析2. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析3. ASP調用WebService轉化成JSON數據,附json.min.asp4. SharePoint Server 2019新特性介紹5. ASP中常用的22個FSO文件操作函數整理6. React+umi+typeScript創建項目的過程7. php網絡安全中命令執行漏洞的產生及本質探究8. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁9. 三個不常見的 HTML5 實用新特性簡介10. php測試程序運行速度和頁面執行速度的代碼
