PreparedStatement方法执行sql语句

时间:2021-06-22 18:04:16   收藏:0   阅读:0

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();
    }
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!