简体   繁体   English

与Glassfish服务器4的MySQL和JSP数据库连接

[英]MySQL and JSP Database connectivity with Glassfish server 4

Here is my code. 这是我的代码。

    **insert.html**
        <html>
            <head>
                <title>Donate Blood !</title>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
            </head>
            <body>
                <form action="store.jsp" method="POST">
                    Name: <input type="text" name="nam"><br>
                    Rollno: <input type="text" name="rno"><br>
                    Blood Group: <input type="text" name="grp"><br>
                    <input type="submit" value="Add me !">
                </form>
            </body>
        </html>

**Store.jsp**
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
            String name = request.getParameter("nam");
            String roll = request.getParameter("rno");
            String group = request.getParameter("grp");

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/blood","root","");
            Statement st = con.createStatement();
            int i=st.executeUpdate("insert into blood(Name,Rollno,BloodGroup) values('+name+','+roll+','+group+')");
        %>

My database.. 我的数据库 在此处输入图片说明

I am running this code in netbeans 8.0. 我正在netbeans 8.0中运行此代码。 I got the error log as 我收到错误日志为 在此处输入图片说明

It shows that data is too long for blood group but i just given 'A+' in that textbox. 它表明数据对于血型来说太长了,但我在该文本框中仅给出了“ A +”。 Whats going wrong. 怎么了 As I am new to JSP please help me. 由于我是JSP的新手,请帮助我。 Thanks in advance. 提前致谢。

Try using PreparedStatement instead to avoid String concatenation mistakes. 尝试改用PreparedStatement以避免String串联错误。

PreparedStatement st = con.prepareStatement("insert into blood(Name,Rollno,BloodGroup) values(?,?,?)");
st.setString(1, name);
st.setString(2, roll);
st.setString(3, group);
st.executeUpdate();

查询必须以int i = st.executeUpdate( “插入血液(Name,Rollno,BloodGroup)值('” + name +“','” + roll +“','” + group +“')” )的形式执行;

The Exception: 例外:

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long..

is says, the data you trying to insert into BloodGroup column is larger then you have specified column data size when creating table. BloodGroup ,您尝试插入BloodGroup列中的数据较大,则在创建表格时已指定了列数据大小。

So fix is: 因此,解决方法是:

change size of BloodGroup column like: 更改BloodGroup列的大小,例如:

ALTER TABLE blood MODIFY BloodGroup varchar(some value more than 5);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM