将String插入JDBC SQLite数据库 [英] Insert String into JDBC SQLite database

查看:166
本文介绍了将String插入JDBC SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个需要本地数据库的Java应用程序.我正在使用带JDBC的SQLite数据库.我是Java本地数据库和JDBC的新手.

I am creating a java application that requires a local database. I am using a SQLite database with JDBC. I am new to Java local database and JDBC.

从互联网上的教程中,我可以算出我正在做的事情,但是对我来说还不是很清楚.我现在正在尝试创建一种方法,该方法可以采用表名和一组字符串并将其添加到表中.

From tutorials on the internet I have just about worked out what I am doing, but it is not very clear to me. I am now trying to create a method that can take in a table name and a set of strings and add them to the table.

我遇到2个问题:

首先,该方法不接受将表作为传入的参数.我知道我可以为每个表创建一个方法,但这效率低下,并且如果可能的话,我希望为所有表使用一个方法.

First, the method does not accept table as a parameter to pass in. I know I can create a method for each table, but this is inefficient and if possible I would like one method to work for all tables.

第二,我无法弄清楚如何将字符串传递到表中,因为要发送到表的数据在SQL语句内部,并且无法识别Java字符串.

Second, I cannot work out how to pass the strings into the table, because the data to be sent to the table is inside a SQL statement and does not recognise the Java string.

以下是到目前为止的方法:

Below is the method so far:

public static void Insert(Table table, String id, String name, String age, String address, String salary) {
    Connection c = null;
    Statement stmt = null;

    try {
        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 COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
                + "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
        //I want this to write the strings passed in by the method, and to the table passed in by the method
        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("Records created successfully");
}

推荐答案

使用准备好的语句代替CreateStatement,如下所示:

Use a Prepared Statement instead of CreateStatement as follows:

PreparedStatement stmt = c.prepareStatement
      ("insert into COMPANY values(?,?,?,?,?)");
      stmt.setInt(1,1);
      stmt.setString(2,"Paul");
      stmt.setInt(3,32);
      stmt.setString(4, "California");
      stmt.setBigDecimal(5, 20000.00);
      stmt.executeUpdate();

您应该为要插入的每个表创建一个准备好的语句. 或者,您可以使用Table作为参数动态构建插入字符串

You should create a Prepared Statement for each Table that you want to insert into. Alternatively you can build up the insert string dynamically with Table as a parameter

String insert_string = "insert into" + Table + "values, etc, etc"

这篇关于将String插入JDBC SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆