11级_Java_曹建波6.19 解决注入问题

本文介绍了一种使用预编译语句防止SQL注入攻击的方法。通过示例代码展示了如何在用户注册和登录过程中利用PreparedStatement来避免潜在的安全风险。

解决注入问题

private voidbtnSubmitActionPerformed(java.awt.event.ActionEvent evt) {

StringuserName = txtName.getText();

Stringpassword = new String(txtPassword.getPassword());

Stringemail = txtEmail.getText();

Stringbirthday = txtBirthday.getText();

Connectioncon = null;

PreparedStatementps = null;

Stringsql = "insert into users(name,password,email,birthday)values(?,?,?,?) ";

try {

con= DBManager.getConnection();

ps= con.prepareStatement(sql);

ps.setString(1,userName);

ps.setString(2, password);

ps.setString(3,email);

ps.setDate(4,Date.valueOf(birthday));

inti =ps.executeUpdate();

if (userName!=null&&password!=null) {

JOptionPane.showMessageDialog(this,"注册成功!");

}else {

JOptionPane.showMessageDialog(this,"注册失败!");

}

}catch (SQLException e) {

// TODO Auto-generatedcatch block

e.printStackTrace();

}finally{

DBManager.dbClose1(ps, con);

}

}

private voidbtnLogonActionPerformed(java.awt.event.ActionEvent evt) {

newLogon().setVisible(true);

}

private voidbtnloginActionPerformed(java.awt.event.ActionEvent evt) {

StringuserName = txtName.getText();

Stringpassword = new String(txtPassword.getPassword());

Connectioncon = null;

//Statement st= null;

PreparedStatementps = null;

ResultSetrs = null;

//String sql= "select id from users where name='" + userName+ "'andpassword='" + password + "'";

Stringsql = "select id from users where name=? andpassword=?";

try {

con= DBManager.getConnection();

//st =con.createStatement();

ps= con.prepareStatement(sql);

ps.setString(1,userName);

ps.setString(2,password);

//rs =st.executeQuery(sql);

rs= ps.executeQuery();

if (rs.next()) {

JOptionPane.showMessageDialog(this,"登陆成功!");

}else {

JOptionPane.showMessageDialog(this,"登陆失败!");

}

}catch (SQLException e) {

e.printStackTrace();

}finally {

DBManager.dbClose(rs,ps, con);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值