这是我的代码:
request.setCharacterEncoding("gbk");
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
conn = new connDB().getConn();
String title = request.getParameter("subject");
String content = request.getParameter("content");
String username = session.getAttribute("username").toString();
String picture = request.getParameter("picture");
if(picture == null)
picture = "tubiao/1.jpg";
if(username != null){
String sql1 = "insert into subject (username,title,time,picture ) values(?,?,?,?)";
pstmt1.setString(1,username);
pstmt1.setString(2,title);
pstmt1.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
pstmt1.setString(4,picture);
pstmt1 = conn.prepareStatement(sql1);
pstmt1.executeUpdate();
}
String sql2 = "insert into content1 (value) values (?)";
pstmt2.setString(1,content);
pstmt2 = conn.prepareStatement(sql2);
pstmt2.executeUpdate();
为什么每次运行总是会报空指针异常呢?错误出在pstmt1.setString(1,username); subject表是自增的。可是username打印出来不是空值啊. 小弟实在是无能为力了。敢问哪位高手能略加指导?不胜感激。
------解决方案--------------------
----------------------------------------------
问题不是 username,而是 pstmt1 的值还是 null,你忘了初始化它了!
应该有类似的这样一行:
pstmt1 = conn.preparedStatement("你的SQL语句");