2017-04-19 64 views
0

我試圖從最後2小時我不知道什麼是錯的。也讓我知道我怎麼能測試,如果連接是全成或不..它是現在..但我仍想知道..使用JDBC在MyQSL中插入多個數據(列表)


錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?)'

我的代碼:

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
static final String DB_URL = "jdbc:mysql://localhost:3306/medicinedb"; 
static final String USER = "root"; 
static final String PASS = ""; 
static final String DRIVER = "com.mysql.jdbc.Driver"; 

public boolean saveMedicine(List<MedicineName> medicineName) throws ClassNotFoundException { 
    Connection conn = null; 
    Statement stmt = null; 

    try { 
     Class.forName(DRIVER); 

     //STEP 3: Open a connection 
     System.out.println("Connecting to database..."); 

     conn = DriverManager.getConnection(DB_URL, USER, PASS); 

     //STEP 4: Execute a query 
     System.out.println("Creating statement..."); 

     stmt = conn.createStatement(); 
     for (MedicineName element : medicineName) { 

      String sql; 
      sql = " insert into medicinename (name, pgurl)" + " values 
      (?, ?)"; 
      System.out.println(conn); 

      PreparedStatement preparedStmt = conn.prepareStatement(sql); 
      preparedStmt.setString(1, element.getName()); 
      preparedStmt.setString(2, element.getPgurl()); 
      stmt.executeUpdate(sql); 
     } 

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

    return true; 
} 
+0

你可以試試用這個'sql =「插入藥名(name,pgurl)的值(?,?)」;' –

+0

同樣的錯誤...... @ YCF_L – doe

+0

你的'name和pgurl'類型是什麼r數據庫 –

回答

0

爲什麼要使用Statement和Prepared語句。您正在使用Statement執行操作。因此它沒有價值。取下聲明

stmt = conn.createStatement(); 

並執行以下操作

PreparedStatement preparedStmt = conn.prepareStatement(sql); 
     preparedStmt.setString(1, element.getName()); 
     preparedStmt.setString(2, element.getPgurl()); 
     //stmt.executeUpdate(sql); 
     preparedStmt .executeUpdate(sql); 
0
  1. 您在stmpreparedStmt之間的搭配,你必須執行preparedStmt而不是stm

  2. 當你要執行多個語句作爲一個單元,再就是其良好的使用聲明批處理工作,而不是例如:

PreparedStatement preparedStmt; String sql; conn.setAutoCommit(false); for (MedicineName element : medicineName) { sql = "insert into medicinename (name, pgurl) values (?, ?)"; System.out.println(conn); preparedStmt = conn.prepareStatement(sql); preparedStmt.setString(1, element.getName()); preparedStmt.setString(2, element.getPgurl()); preparedStmt.addBatch(sql); } preparedStmt.executeBatch(); conn.commit();
0

使用

String sql = "insert into medicinename (name, pgurl) values (?, ?)"; 
        PreparedStatement preparedStmt = conn.prepareStatement(sql); 
        preparedStmt.setString (1, element.getName()); 
        preparedStmt.setString (2, element.getPgurl()); 
        preparedStmt.executeUpdate(); 

you should delete executeUpdate(sql); to executeUpdate(); 
相關問題