Java之PreparedStatement的使用詳解
PreparedStatement常用的方法:
void setObject(int parameterIndex, Object x, int targetSqlType)
parameterIndex the first parameter is 1, the second is 2, …占位符參數(shù)索引是從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)
執(zhí)行操作:
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.加載驅(qū)動Class.forName(driverClass);//4,獲取連接con = DriverManager.getConnection(url, user,password);String sql = 'insert into customers(name,birth) value(?,?)';//預(yù)編譯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,執(zhí)行操作ps.execute();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {//7,關(guān)閉資源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
執(zhí)行結(jié)果:
到此這篇關(guān)于Java之PreparedStatement的使用詳解的文章就介紹到這了,更多相關(guān)Java之PreparedStatement內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. XML入門精解之結(jié)構(gòu)與語法2. SpringMVC+Jquery實(shí)現(xiàn)Ajax功能3. 匹配模式 - XSL教程 - 44. ASP.NET MVC使用異步Action的方法5. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera6. JS中map和parseInt的用法詳解7. ASP中if語句、select 、while循環(huán)的使用方法8. XML入門的常見問題(一)9. 存儲于xml中需要的HTML轉(zhuǎn)義代碼10. 詳談ajax返回數(shù)據(jù)成功 卻進(jìn)入error的方法
