读书人

关于向数据库插入数据的有关问题

发布时间: 2012-01-13 22:43:29 作者: rapoo

关于向数据库插入数据的问题~
RT,我数据库设置的news_id为自增主键,然后插入方法写的这样:

Java code
public void save()throws Exception{    try    {        String newstheme=form.getNews_theme();        String newsauthor=form.getNews_author();        String newsdate=form.getNews_date();        String newsdetail=form.getNews_detail();        String newsurl=form.getNews_url();        String sql="insert into s_news values('"+newstheme+"','"+newsauthor+"','"+newsdate+"','"+newsdetail+"','"+newsurl+"')";        PreparedStatement pstmt=conn.prepareStatement(sql);        pstmt.executeUpdate(sql);        pstmt.close();        conn.commit();        conn.close();    }    catch(Exception e)    {        conn.rollback();        throw new Exception(e.getMessage());    }}


结果插入不成功,请问代码怎么改,还有这里是不是也要改?
Java code
public class NewsForm extends ActionForm{    private String news_id;    private String news_theme;    public String getNews_id() {        return news_id;    }    public  void setNews_id(String news_id)    {        this.news_id = news_id;    }    public String getNews_theme() {        return news_theme;    }    public void setNews_theme(String news_theme) {        this.news_theme = news_theme;    }


这是action .
Java code
    public ActionForward addnews(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)    {        NewsForm AllNewsActionForm=(NewsForm)form;        DataSource ds = getDataSource(request,"struts");        try        {            ActionNews actionNews= new ActionNews(AllNewsActionForm,ds);             actionNews.save();            request.setAttribute("info","保存成功!");                    }        catch(Exception e)        {            request.setAttribute("info",e.getMessage());        }        return mapping.findForward("save");            }


页面没有输入 <html:text property="news_id" /> 这一列

[解决办法]
insert into s_news('这里把所有非自增的字段名全写出') values
[解决办法]
和 id 没有关系 你看一下错误是什么 类型还是长度
[解决办法]
插入不成功的错误贴出来。。。
还有
String sql="insert into s_news values('"+newstheme+"','"+newsauthor+"','"+newsdate+"','"+newsdetail+"','"+newsurl+"')";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.executeUpdate(sql);

你使用了prepareStatement,但是你的参数没有用?,去设置。。直接拼接到字符串里,,那为何不用Statement?这样用prepareStatement毫无意义可言。。。
[解决办法]
探讨

insert into s_news('这里把所有非自增的字段名全写出') values

[解决办法]
sql语法不通过~,就是说你的sql写的不对,学习一下sql吧
[解决办法]
探讨

引用:
sql语法不通过~,就是说你的sql写的不对,学习一下sql吧


再问个别的问题,自动增加的主键id删除部分记录后,能不能使下一条id号按照当前顺序添加,比如删了5,如何让下一条ID还是5.


这个有办法吗?

[解决办法]
探讨
引用:


sql语法不通过~,就是说你的sql写的不对,学习一下sql吧


再问个别的问题,自动增加的主键id删除部分记录后,能不能使下一条id号按照当前顺序添加,比如删了5,如何让下一条ID还是5.


这个有办法吗?

读书人网 >Java Web开发

热点推荐