mysql的jdbc防止注入占位符_JDBC_mysql---防sql注入,存储图片

packagePreparedStatement_sql注入;importjava.io.File;importjava.io.FileInputStream;importjava.io.InputStream;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.util.Scanner;importorg.junit.After;importorg.junit.Before;importorg.junit.Test;public classPreparedStatement_sql {//用?作为占位符号

/*** 保存图片mysql中用longblob

*@throwsException*/@Testpublic void saveImg() throwsException{

String sql= "insert into stud values(66,?,?)";

PreparedStatement pst=con.prepareStatement(sql);//声明图片的信息

File file = new File("./img/a.jpg");

InputStream in= newFileInputStream(file);//设置参数到pst中

pst.setString(1, "ss");

pst.setBinaryStream(2,in);//执行

pst.executeUpdate();

}/*** 防止sql注入

*

*@throwsException*/@Testpublic void regWithPre() throwsException {

Scanner sc= newScanner(System.in);

System.err.println("输入id ,name");

String id=sc.nextLine();

String name=sc.nextLine();

String sql= "insert into stud values(?,?)";//preparedstatement pst 接收sql//执行sql语句再设置参数

PreparedStatement pst =con.prepareStatement(sql);//编译好后设置参数//设置值要从1开始

pst.setString(1, id);

pst.setString(2, name);

pst.executeUpdate();

}/*** 判断数据库里是否有值

*

*@throwsException*/@Testpublic void loginPst() throwsException {

Scanner sc= newScanner(System.in);

String nm=sc.nextLine();

String id=sc.nextLine();

String sql= "select * from stud where id=? and name=?";

PreparedStatement pst=con.prepareStatement(sql);

pst.setString(1, id);

pst.setString(2, nm);

System.err.println(sql);

ResultSet rs= pst.executeQuery();//判断是否有值

if(rs.next()) {

System.err.println("你登录成功,你好欢迎你..");

}else{

System.err.println("你登录不成功。。。");

}

}

@Before//执行Test前执行

public void getCon() throwsException {

Class.forName("com.mysql.jdbc.Driver");

String url= "jdbc:mysql://127.0.0.1:3306/abc?useUnicode=true&characterEncoding=utf8";

con= DriverManager.getConnection(url, "root", "1234");//con.close();//System.err.println(con);

}

@After//执行Test后执行

public void closeConn() throwsException {if (con != null || !con.isClosed()) {

con.close();

}

}privateConnection con;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值