PreparedStatement方法執行sql語句


PreparedStatement方法執行sql語句

package com.lwb.preparedstatement.crud;

import org.junit.jupiter.api.Test;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Properties;

public class PreparedStatementUpdateTest {
    @Test
    public void testInsert() throws Exception {
        InputStream is=ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");

        Properties pros=new Properties();
        pros.load(is);

        String user=pros.getProperty("user");
        String password=pros.getProperty("password");
        String url=pros.getProperty("url");
        String driverClass=pros.getProperty("driverClass");
        //加載驅動
        Class.forName(driverClass);

        //獲取連接
        Connection conn= DriverManager.getConnection(url,user,password);
//        System.out.println("test5:  "+conn);
//        4、預編譯sql語句,返回PreparedStatement的實例
        String sql="insert into customers(name,email,birth)values(?,?,?)";
        PreparedStatement ps=conn.prepareStatement(sql);
        //5、填充占位符
        ps.setString(1,"abc");
        ps.setString(2,"abc@haha.com");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date=sdf.parse("1000-01-01");
        ps.setDate(3,  new Date(date.getTime()));
        //6、執行操作
        ps.execute();
        //7、關閉資源
        ps.close();
        conn.close();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM