2016-06-08 3 views
0

메신저 SQLite에서 시작, 내 db 만들고 연결 작동합니다. 내가 (DB를이 비어) 나는 다음과 같은 오류가 값을 삽입하려고 할 때 :자바 - SQLite에서 값을 삽입하는 방법은 무엇입니까?

java.sql.SQLException: near ".684": syntax error

import java.sql.*; 

public class connection{ 
    String route = "C:\\Freeman SA.db"; 
    Connection c = null; 
    Statement stat = null; 
    String op; 

    public void connect(){ 
     try{ 
      c = DriverManager.getConnection("jdbc:sqlite:"+route); 
      if (c!=null) 
       System.out.println("Connected to db."); 
     } 
     catch (SQLException ex) { 
      System.err.println("Couldn't connect."+ex.getMessage()); 
     } 
    } 

    public void insert_DB(String NAME, String LNAME, String ID, int AGE, int TIME, int SALARY) throws SQLException{ 
     connect(); 
     try { 
      stat = c.createStatement(); 
      op = "INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES (" + NAME + ", " + LNAME + ", " + ID + ", " + AGE + ", " + TIME + ", " + SALARY + ");"; 
      stat.executeUpdate(op);  //Here is the problem 
      stat.close(); 
     } 
     catch (SQLException e) { 
      System.err.println(e.getClass().getName() + ": " + e.getMessage()); 
     } 
     c.close(); 
    } 
} 

홈페이지를.

public static void main(String[] args) throws IOException { 

     connection n = new connection(); 
     try { 
      n.insert_DB("Charlie", "White", "18.954.621-K", 21, 2, 650000); 
     } catch (SQLException ex) { 
      Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

PD : 여기에서 배우고 : http://www.tutorialspoint.com/sqlite/sqlite_java.htm

답변

1

그것은 같은 문자열을 연결하여 SQL 문을 작성하는 나쁜 생각입니다. SQL 인젝션 공격과 Little Bobby Tables에 대한 연구를 수행하십시오.

PreparedStatement은 더 좋은 아이디어입니다. 유효성 검사 후 변수를 바인딩하십시오.

import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 
import java.sql.Statement; 

/** 
* Demo RenumerationDao 
* Created by Michael 
* Creation date 6/8/2016. 
* @link https://stackoverflow.com/questions/37714254/java-how-can-i-insert-values-in-sqlite/37714292#37714292 
*/ 
public class RenumerationDao { 

    private static final String INSERT_SQL = "INSERT INTO Remuneraciones(Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES(?, ?, ?, ?, ?, ?)"; 

    private Connection connection; // Better to get this from a pool. 

    public RenumerationDao(Connection connection) { 
     this.connection = connection; 
    } 

    public int insert(String firstName, String lastName, String id, int age, int timeInHours, int salary) { 
     int numRowsInserted = 0; 
     PreparedStatement ps = null; 
     try { 
      ps = this.connection.prepareStatement(INSERT_SQL); 
      ps.setString(1, firstName); 
      ps.setString(2, lastName); 
      ps.setString(3, id); 
      ps.setInt(4, timeInHours); 
      ps.setInt(5, age); // You'll have to update this each and every year. BirthDate would be better. 
      ps.setInt(6, salary); 
      numRowsInserted = ps.executeUpdate(); 

     } catch (SQLException e) { 
      e.printStackTrace(); 
     } finally { 
      close(ps); 
     } 
     return numRowsInserted; 
    } 

    public static void close(Statement statement) { 
     try { 
      if (statement != null) { 
       statement.close(); 
      } 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

나에게 고마워했습니다. :) – Camg

0

나는 String op 인쇄 나이 보여 :

INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES (Charlie, White, 18.954.621-K, 21, 2, 650000); 
나는 문자열 값에 따옴표 누락 된

, 그것은 같은 것을해야합니다을이 당신의 인생을 더 나은 만드는 경우

보기 이 :

INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES ('Charlie', 'White', '18.954.621-K', 21, 2, 650000); 

기능을 고정하고

012 일
public void insert_DB(String NAME, String LNAME, String ID, int AGE, int TIME, int SALARY) throws SQLException{ 
     connect(); 
     NAME = "'"+NAME+"'"; 
     LNAME = "'"+LNAME+"'"; 
     ID = "'"+ID+"'"; 
     try { 
      stat = c.createStatement(); 
      op = "INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES (" + NAME + ", " + LNAME + ", " + ID + ", " + AGE + ", " + TIME + ", " + SALARY + ");"; 
      stat.executeUpdate(op);  //Here is the problem 
      stat.close(); 
     } 
     catch (SQLException e) { 
      System.err.println(e.getClass().getName() + ": " + e.getMessage()); 
     } 
     c.close(); 
    } 
} 

답장과 독자에게 감사드립니다.

+1

학습 단계가 완료되면 나중에도 PreparedStatement를 선호해야합니다. – duffymo

+1

일부 값에 따옴표가 포함되어 있으면이 값이 올라갑니다. –

+0

네 말이 맞아, 나는 그것에 대해 생각하지 않았다. – Camg

관련 문제