【问题标题】:Inserting array elements sequentially into a database java将数组元素顺序插入数据库java
【发布时间】:2015-11-13 23:10:22
【问题描述】:

例如,如果我有一个字符串数组列表,我如何将它们按顺序放入数据库中。 例如,如果我的数组列表是:“john”、“sally”、“rob” 我怎样才能把它放到我的数据库中,这样第 1 行是 john,第 2 行是 sally,第 3 行是 rob。 我的想法是这样的:

for(int i = 0; i < array.size(); i++){
     query = "insert into database values(i);
}

但我不确定这是否是正确的方法,因为我还将向数据库中插入数组以外的其他值。

【问题讨论】:

  • 你如何定义“行”?记录是否具有定义行号的数字主键?而且,其他值...除了数组,这到底是什么意思?你能提供更多信息丰富的例子吗?

标签: java mysql arrays


【解决方案1】:

我假设您的意思是简单的插入;

首先你有数据库连接,像这样:

public class DBConnection {

final private String url = "jdbc:mysql://localhost/";
final private String databaseName = "test";
final private String user = "root";
final private String password = "159753";

public Connection Connect() {
    Connection c = null;
    try {
        c = DriverManager.getConnection(url + databaseName, user, password);
    } catch (SQLException ex) {
        Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
    }
    return c;
}}

下面是一个简单的插入示例:

    public static void main(String[] args) {
    Connection con = new DBConnection().Connect();
    String sql = "INSERT INTO nameTable (name) values (?)";
    PreparedStatement stmt;
    try {
        stmt = con.prepareStatement(sql);
        List<String> names = new ArrayList();
        names.add("John");
        names.add("Sally");
        names.add("Rob");
        for (String name : names) {
            stmt.setString(1, name);
            stmt.execute();
        }
        stmt.close();
        con.close();
    } catch (SQLException ex) {
        System.err.println("Error = " + ex);
    }
}}

PS:但是您也可以使用 Java Persistence API。 wikibook 是一个很好的参考资源

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-24
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2020-01-28
    相关资源
    最近更新 更多