Java数据库插入失败

时间:2017-08-09 14:54:25

标签: java mysql database jdbc

我的程序应该从xml文件中获取数据并将它们放入db。

我使用phpmyadmin mysql数据库。

我成功地从XML获取数据,但是当我尝试将其放入数据库时​​,它失败了。

DBInput.java //带按钮的JFrame。当按下按钮时,程序应该将数据放入数据库中。

package jSpyDroidEclipse;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JFileChooser;

import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.spi.CurrencyNameProvider;
import java.awt.event.ActionEvent;

public class DBInput extends JFrame {

private JPanel contentPane;
private File xmlFile;

/**
 * Launch the application.
 */


public String strStr(String haystack, String needle) {
      if(haystack==null || needle==null) return null; 
      int hLength=haystack.length(); 
      int nLength=needle.length(); 
      if(hLength<nLength) return null; 
      if(nLength==0) return haystack;
      for(int i=0; i<=hLength-nLength; i++)
      {
        if(haystack.charAt(i)==needle.charAt(0))
        {
          int j=0; 
          for(; j<nLength; j++)
          {
            if(haystack.charAt(i+j)!=needle.charAt(j))
            {
              break; 
            }
          }
          if(j==nLength) return haystack.substring(i) ; 
        }  
      }
      return null; 
    }


public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                DBInput frame = new DBInput();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public DBInput() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton b_browse = new JButton("Browse");
    b_browse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser fileChooser = new JFileChooser();

             fileChooser.setCurrentDirectory(new java.io.File("user.home"));
                fileChooser.setDialogTitle("Select the XML file");
                fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                if (fileChooser.showOpenDialog(b_browse) == JFileChooser.APPROVE_OPTION) {
                    xmlFile = fileChooser.getSelectedFile();


                    BufferedReader bufferedReader = null;
                    try {
                        bufferedReader = new BufferedReader(new FileReader(xmlFile));
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    String currentLine = null;
                    try {
                        currentLine = bufferedReader.readLine();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }


                    StringBuilder xmlCode = new StringBuilder();
                    xmlCode.append(currentLine);

                    if((currentLine!=null) && !currentLine.equals(""))
                    {
                        try {
                            while((currentLine = bufferedReader.readLine())!=null)
                            {
                                xmlCode.append(currentLine);
                            }
                        } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        }
                    }


                    String sXMLCode = xmlCode.toString();

                    DBConnect connect = new DBConnect();
                    while(sXMLCode!=null)
                    {

                        String adv_name = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_ADV_NAME);
                        String category = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_CATEGORY);
                        String curency = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_CURENCY);
                        String free_shiping = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_FREE_SHIPPING);
                        String gift = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_GIFT_INCLUDED);
                        String manufacturer = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_MANUFACTURER);
                        String price_no_vat = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_PRICE_NO_VAT);
                        String price_vat = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_PRICE_VAT);
                        String PRODUCT_AFF_LINK = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_PRODUCT_AFF_LINK);
                        String PRODUCT_CODE = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_PRODUCT_CODE);
                        String PRODUCT_DESC = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_PRODUCT_DESC);
                        String PRODUCT_NAME = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_PRODUCT_NAME);
                        String PRODUCT_PIC = XMLParser.getItem(new String(sXMLCode), XMLParser._TAG_PRODUCT_PIC);


                        String query = "INSERT INTO PRODUCTS(product_code, adv_name, category, manufacturer, gift_included, product_name, product_desc, product_aff_link, product_pic, price_no_vat, price_vat, free_shipping) VALUES("+
                                                            PRODUCT_CODE + "," + adv_name + "," + category + "," + manufacturer + "," + gift + "," + PRODUCT_NAME + "," + PRODUCT_DESC + "," + PRODUCT_AFF_LINK + "," + PRODUCT_PIC + "," + price_no_vat + "," + price_vat + "," + free_shiping + ");";

                        connect.insertData(query);                      


                        //shifting to next product
                        String code = xmlCode.toString();
                        sXMLCode = strStr(sXMLCode.substring(1), XMLParser._TAG_PRODUCT);
                        //connect.disconnect();
                        //connect = null;
                    }
                }
        }
    });
    b_browse.setBounds(164, 103, 97, 25);
    contentPane.add(b_browse);
    }
}

DBConnect.java

package jSpyDroidEclipse;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.PreparedStatement;

public class DBConnect {

private Connection connection;
private Statement statement;
private ResultSet resultSet;
private PreparedStatement preparedStatement;

public DBConnect()
{
    try {
        Class.forName("com.mysql.jdbc.Driver");
        //TODO: hardcoded
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/admin", "root", "");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}


// it runs the query and returns the dataset
// query is supposed to be a select statement
// TODO: CHECK query to be a select statement
public ResultSet selectData(String query)
{
    try {
        statement = connection.createStatement();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        resultSet = statement.executeQuery(query);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        statement.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        resultSet.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return resultSet;
}



//TODO: set type ResultSet and return inserted data
public void insertData(String query)
{
    try {
        preparedStatement = (PreparedStatement) connection.prepareStatement(query);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        preparedStatement.execute();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


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

public void updateData(String query)
{

}

public static void main(String[] args) {
     DBConnect connect = new DBConnect();
}

public void disconnect()
{
    try {
        connection.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

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

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

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

    connection = null;
    preparedStatement = null;
    resultSet = null;
    statement = null;
 }
}

我还测试了插入方法没有那个while循环,它可以工作。

错误讯息:

  

java.sql.SQLException:没有为参数1指定值   在com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
  在com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
  在com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)

3 个答案:

答案 0 :(得分:3)

  1. 首先:您使用PrepapredStatement的方式错误,
  2. 第二:我假设像PRODUCT_CODEadv_name这样的类型值是String,而String应该在两个引号之间'value'
  3. 要解决您的问题,您可以:

    1. 而不是public void insertData(String query)你可以创建两个方法,一个返回准备好的语句,第二个关闭语句
    2. 为每个对象创建一个方法,该方法接受您的Object,调用prepapred语句,执行语句,最后关闭语句
    3. 这是一个简单的例子:

      String query = "INSERT INTO PRODUCTS(product_code, adv_name, category, manufacturer, "
              + "gift_included, product_name, product_desc, product_aff_link, "
              + "product_pic, price_no_vat, price_vat, free_shipping) VALUES(?, ?, ?, ....)";
      try (PreparedStatement pstm = getPreparedStatement(query)) {
          pstm.setString(1, PRODUCT_CODE);
          pstm.setString(2, adv_name);
          pstm.setString(3, category);
          ...
          pstm.execute();
          closeStatement(pstm);
      }
      

答案 1 :(得分:2)

你似乎没有使用撇号。至少它应该是这样的: -

   String query = "INSERT INTO PRODUCTS(product_code, adv_name, category, manufacturer, gift_included, product_name, product_desc, product_aff_link, product_pic, price_no_vat, price_vat, free_shipping) 
   VALUES('"+ PRODUCT_CODE + "','" + adv_name + "', [etc]

..虽然这会让你对SQL注入攻击开放,所以我会使用参数。

答案 2 :(得分:2)

确定如下:

String query = "INSERT INTO PRODUCTS(product_code, adv_name, category, manufacturer, gift_included, product_name, product_desc, product_aff_link, product_pic, price_no_vat, price_vat, free_shipping) VALUES("+
                                                            PRODUCT_CODE + "," + adv_name + "," + category + "," + manufacturer + "," + gift + "," + PRODUCT_NAME + "," + PRODUCT_DESC + "," + PRODUCT_AFF_LINK + "," + PRODUCT_PIC + "," + price_no_vat + "," + price_vat + "," + free_shiping + ");";

您需要更改以下代码:

'"+PRODUCT_CODE+"', 

还有其他变量。

您可以感觉到这一点(字符串连接)是一种可行的查询方式。您需要使用PreparedStatement。这也将避免SQL injection