在MySQL中插入数据时出错

时间:2012-04-04 17:31:37

标签: mysql java-ee servlets

当我在db表中执行插入时,会发生异常,其中包含:

Data truncation error in mySQL while inserting data..

目前: - >

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'branchname' at row 1

列类型为varchar

JSP:

<form action="BranchServlet" method="post">
<table align="center">
<tr>
<td align="center" colspan="2"><hr>Add Branch Details<hr></td>
</tr>


<tr>
<td align="left">Branch Name</td>
<td align="center"><input type="text" name="branchname"></td>
</tr>
<tr>
<td align="left">Branch Code</td>
<td align="center"><input type="text" name="branchcode"></td>
</tr>
<tr>
<td align="center">

</td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" Value="Submit"></td>
</tr>
</table>
</form>

的Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {

        String bname = request.getParameter("branchname");
        String bcode = request.getParameter("branchcode");

        BranchModel bm = new BranchModel();
        BranchDAO bd = new BranchDAO();

        bm.setBranchcode(bcode);
        bm.setBranchname(bname);

        bd.insert(bm);

        response.sendRedirect("branches.jsp");
    }

DAO方法:

public void insert(BranchModel m)
    {
        try{
            Class.forName(driver);
            con = DriverManager.getConnection(url+db,"root","root");
            Statement st = con.createStatement();

            st.executeUpdate("insert into branches values('"+m.getBranchcode()+"','"+m.getBranchname()+"')");
            System.out.println("record inserted");
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }

1 个答案:

答案 0 :(得分:4)

您说该列的类型为varchar,但不是varchar的大小。这似乎是你问题的根源。我没有看到任何验证强制限制文本输入的大小。输入验证需要将输入大小限制为相应varchar列的大小。