JSP String.format() 格式化问题 java.util.IllegalFormatConversionException: g != java.lang.String

遇到的问题

String.format() 格式化问题

报错:
10-23-2019java.util.IllegalFormatConversionException: g != java.lang.String

原因:

String p_id=Bytes(request.getParameter("p_id"));
String p_type=Bytes(request.getParameter("p_type"));
String p_name=Bytes(request.getParameter("p_name"));
float p_price=Float.parseFloat(request.getParameter("p_price"));
int p_quantity=Integer.parseInt(request.getParameter("p_quantity"));
String p_image=Bytes(request.getParameter("p_image"));
String p_description=Bytes(request.getParameter("p_description"));

String strQuery=String.format
("insert into Product values p_type='%s'+p_id='%s'+p_name='%s'+p_price='%d'+p_quantity='%g'+p_image='%s'+p_description='%s'","p_type","p_id","p_name","p_price","p_quantity","p_image","p_description");
//p_quantity定义的类型是整型,我却在String.format()里给它格式化成浮点型。
//在String.format()里整型的格式化为'%d'。

解决办法:

将 p_quantity=’%g‘ 改成 p_quantity=’%d’ 。

上面的内容是我照着书上打的,后面自己琢磨了会,又问了老师,终于得出了下面可运行的代码了

<%
try{
	Class.forName("com.mysql.jdbc.Driver");
	String url="jdbc:mysql://localhost:3306/shopssystem?useUnicode=true&characterEncoding=UTF-8";
	String user="root";
	String password="";
	Connection conn=DriverManager.getConnection(url, user, password);
	Statement sm=conn.createStatement();
	request.setCharacterEncoding("UTF-8");
	//这句是将字符都转为UTF-8型,就不用在像上面一样,每句前面加byte。
	String p_id=request.getParameter("p_id");
	String p_type=request.getParameter("p_type");
	String p_name=request.getParameter("p_name");
	float p_price=Float.parseFloat(request.getParameter("p_price"));
	int p_quantity=Integer.parseInt(request.getParameter("p_quantity"));
	String p_image=request.getParameter("p_image");
	String p_description=request.getParameter("p_description");
	//String strQuery="Select Top 5 p_id,p_type,p_name,p_price,p_quantity from product order by p_time desc";
	//String p_time=String.valueOf(date.getMonth()+1)+"-"+date.getDate()+"-20"+String.valueOf(date.getYear()).substring(1);
	SimpleDateFormat formater =new SimpleDateFormat("MM-dd-yyyy");
  	String p_time = formater.format(new Date()); %>	<%=p_time %>
	<%String strQuery=String.format	("insert into product value ('%s','%s','%s','%f','%d','%s','%s','%s')",p_type,p_id,p_name,p_price,p_quantity,p_image,p_description,p_time);
	//executeUpdate将执行数据库的增、删、改操作,同时返回操作所影响的行数
	int i=sm.executeUpdate(strQuery);
	out.print(i);
	if(i>0){
		out.print("<font size=4pt color='red'>"+"商品添加成功!"+"</font>");
	}
	else{
		out.print("<font size=4pt color='red'>"+"商品添加失败!"+"</font>");
	}
}catch(Exception e){
	out.println(e.toString());
}%>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值