繁体   English   中英

将数据插入表sqlite Java

[英]Insert data into table sqlite java

我在将数据插入我的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”。 哪个更好?

您必须使用PreparedStatement。 另外,强烈建议在Java-8之后将数据库连接视为AutoClosables 您可以阅读try-with-resources语句以获取操作方法。 最后,不要使用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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM