Java Servlet 插入 MySQL

标签 java mysql database servlets insert

<分区>

我正在尝试将 HTML 表单中的记录插入到 MySQL 数据库中。我有 HTML 和 Jquery,但我的 Servlet 有问题。我没有立即注意到它有什么问题,但如果我能在正确的方向上找到一个点,我就可以越过我现在的位置。谢谢

package com.david.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;


/**
 * Servlet implementation class myForm
 */

public class myForm extends HttpServlet {

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
        {
              //Get parameters
            String id = request.getParameter("ID");
            String fname = request.getParameter("FirstName");
            String lname = request.getParameter("LastName");


            //Get Connection
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("Found a driver");
            Connection dbConnect = null;
            try {
                dbConnect = getConnection("localhost", 7001);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NamingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            System.out.println("Made a connection");


                //Create Query
            String query = "INSERT INTO test.customer (ID, FirstName, LastName) " + 
                    "VALUES (" + id + ", " + fname + ", " + lname + ")";
            PreparedStatement dbStatement = null;
            try {
                dbStatement = dbConnect.prepareStatement(query);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //Execute Query
            try {
                dbStatement.executeUpdate(query);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //close connection
            try {
                dbStatement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                dbConnect.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }





public Connection getConnection(String server, int port)
        throws SQLException, NamingException {
    Context ctx = null;
    Hashtable ht = new Hashtable();
    ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    ht.put(Context.PROVIDER_URL, "t3://"+server+":"+port);
    ctx = new InitialContext(ht);
    DataSource ds = (javax.sql.DataSource) ctx.lookup ("localmysql");
    Connection conn =  ds.getConnection();
    //conn.setAutoCommit( true );
    return conn;
}    





}

最佳答案

fnamelname 文本字段周围缺少一些单引号:

String query = "INSERT INTO test.customer (ID, FirstName, LastName) " + 
           "VALUES (" + id + ", '" + fname + "', '" + lname + "')";

注意:最安全的方法是使用 PreparedStatement 占位符,而不是进行 String 连接。他们不仅会防止SQL Injection攻击,但他们也会管理引号字符。

String query = "INSERT INTO test.customer (ID, FirstName, LastName) VALUES (?,?,?)";
PreparedStatement dbStatement = dbConnect.prepareStatement(query);
dbStatement.setInt(1, Integer.parseInt(id));
dbStatement.setString(2, fname);
dbStatement.setString(3, lname);

(Id 字段是通常 INTEGER 类型)

关于Java Servlet 插入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16425224/

相关文章:

mysql - 有没有办法强制至少一列不为空

php - Laravel 5.3 使用单个 SQL 查询和缓存需要 1.9 秒

database - 在字符串 eq 中使用未初始化的值 $end_time1 .......perl 中的错误

java - Spring框架: Register conversion-service with java config

java - 斯坦福 CoreNLP : input with one sentence per line

java - 使用 GeoJson 向 google map 添加标记

java - 覆盖预定义数组

php - MySQL (# of Products in Category) COUNT() with/L​​EFT JOIN and ON 2 Tables

sql - 同步客户端-服务器数据库

PHP 和 MySQL : Arranging rows from separate tables together and expression to determine row origin