将数据插入表sqlite Java

时间:2019-02-17 09:34:04

标签: java database sqlite

我无法将数据插入我的sqlite表中。我想将变量插入列而不是固定数据

Fixed data:
"INSERT INTO DATOS (ID,NOMBRE,GRUPO,TUTOR) " +
                "VALUES (1, 'Paul', 32, 'California');";

That i want:
"INSERT INTO DATOS (ID,NOMBRE,GRUPO,TUTOR) " +
                "VALUES (variableID, variableName, variableNumber, variableCity);";

我一直在阅读文档,但无法查到,请您帮我。目前,我设法创建数据库并手动插入数据:

package com.proyecto.demo;

import java.sql.*;

public class SQLiteJDBC {
public static void main( String args[] ) {
  Connection c = null;
  Statement stmt = null;

  try { // Create the table
     Class.forName("org.sqlite.JDBC");
     c = DriverManager.getConnection("jdbc:sqlite:test.db");
     System.out.println("Paso 1: Base de datos creada");

     stmt = c.createStatement();
     String sql = "CREATE TABLE DATOS " +
                    "(ID INT PRIMARY KEY     NOT NULL," +
                    " NOMBRE           TEXT    NOT NULL, " + 
                    " GRUPO            TEXT     NOT NULL, " + 
                    " TUTOR        INT)"; 
     stmt.executeUpdate(sql);
     stmt.close();
     c.close();
  } catch ( Exception e ) {
     System.err.println( e.getClass().getName() + ": " +  e.getMessage() );
     System.exit(0);
  }

  try { // Insert date to the table (here is where i have problems)
    System.out.println("Paso 2: Conectar Base de datos");
     Class.forName("org.sqlite.JDBC");
     c = DriverManager.getConnection("jdbc:sqlite:test.db");
     c.setAutoCommit(false);
     System.out.println("Opened database successfully");

     stmt = c.createStatement();
     String sql = "INSERT INTO DATOS (ID,NOMBRE,GRUPO,TUTOR) " +
                    "VALUES (1, 'Paul', 32, 'California');"; 
     stmt.executeUpdate(sql);

     stmt.close();
     c.commit();
     c.close();
  } catch ( Exception e ) {
     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
     System.exit(0);
  }
  System.out.println("All inserted!");
 }
}

PD:一个用户建议我使用SQL脚本执行我的任务,但是另一个用户告诉我使用“ preparedstatement”。哪个更好?

1 个答案:

答案 0 :(得分:1)

您必须使用PreparedStatement.。此外,强烈建议使用Java-8将数据库连接视为AutoClosables。您可以阅读the try-with-resources Statement,以获取有关操作方法的信息。最后,不要使用Exception类来捕获异常。捕获大多数情况下要获得的异常,在您的情况下为SQLException

以下是上述情况的完整示例:

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

public class SQLiteSample {
    private static final String URL = "jdbc:sqlite:data.db";

    public static void main(String[] args) {
        createDb();
        createTable();
        insertPerson("Thomas", 15);
        insertPerson("Walter", 32);
    }

    private static void insertPerson(String name, int age) {
        final String SQL = "INSERT INTO persons VALUES(?,?)";
        try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement(SQL);) {
            ps.setString(1, name); // First question mark will be replaced by name variable - String;
            ps.setInt(2, age); // Second question mark will be replaced by name variable - Integer;
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void createTable() {
        final String SQL = "CREATE TABLE IF NOT EXISTS persons (name TEXT, age INTEGER);";
        // This SQL Query is not "dynamic". Columns are static, so no need to use
        // PreparedStatement.
        try (Connection con = getConnection(); Statement statement = con.createStatement();) {
            statement.executeUpdate(SQL);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void createDb() {
        try (Connection conn = getConnection()) {
            if (conn != null) {
                conn.getMetaData();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL);
    }
}