java jdbc preparestatement_JAVA JDBC prepareStatement 添加数据

我们使用prepareStatement来操作数据库,可以防止sql注入,并且无需拼接sql语句.

核心代码:

String sql = "insert into customers(name,email,birth)values(?,?,?)";

ps = connection.prepareStatement(sql);

ps.setString(1,"哪吒");

ps.setString(2,"nezha@gamail.com");

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Date date = sdf.parse("1000-01-01");

ps.setDate(3, new java.sql.Date(date.getTime()));

ps.execute();

完整代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

InputStream is = connectTest.class.getClassLoader().getResourceAsStream("jdbcInfo.properties");

Properties pro = new Properties();

pro.load(is);

String user = pro.getProperty("user");

String password = pro.getProperty("password");

String url = pro.getProperty("url");

String driverClass = pro.getProperty("driverClass");

//利用反射

Connection connection = null;

PreparedStatement ps = null;

try {

Class.forName(driverClass);

connection = DriverManager.getConnection(url,user,password);

System.out.println(connection);

String sql = "insert into customers(name,email,birth)values(?,?,?)";

ps = connection.prepareStatement(sql);

ps.setString(1,"哪吒");

ps.setString(2,"nezha@gamail.com");

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Date date = sdf.parse("1000-01-01");

ps.setDate(3, new java.sql.Date(date.getTime()));

ps.execute();

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

} catch (ParseException e) {

e.printStackTrace();

} finally {

if(ps!=null)

try {

ps.close();

} catch (SQLException e) {

e.printStackTrace();

}

if(connection!=null)

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

View Code

标签:ps,JDBC,JAVA,String,prepareStatement,pro,connection,sql,new

来源: https://www.cnblogs.com/superxuezhazha/p/12395673.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值