gpt4 book ai didi

java - JDBC程序从一个表中选择数据并插入到不同数据库中的另一个表中

转载 作者:行者123 更新时间:2023-11-29 14:03:38 25 4
gpt4 key购买 nike

我是 java 的新手,我正在尝试将数据从 old_db 插入到 new_db。我已经尝试了一个程序来做到这一点,它显示了类似“语法错误”的错误,无法找到错误的原因。

程序必须连接到 2 个 postgres 数据库并选择表中的数据并将它们插入到另一个数据库表。两个表具有相同的字段和数据类型。

import java.sql.* ;   
public class con2
{
public static void main( String[] args )
{
try
{
Connection con = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/old_db","postgres","password");
try
{
Connection con1 = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/new_db","postgres","password");

Statement st = con.createStatement();
Statement st1 = con1.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM users");



int val = st1.executeUpdate("insert into users("+"'rs()'"+")");

rs.close();
st.close();
st1.close();



}
catch(SQLException e)
{
System.out.println( "could not get JDBC connection for new_db: " + e );
}
}
catch(SQLException e)
{
System.out.println( "could not get JDBC connection for old_db: " + e );
}
}
}

我正在使用 jdbc4

最佳答案

我编写了如下所示的程序,它正在运行。

感谢您的建议。

import java.sql.*;
import java.io.*;
import java.util.*;

public class test1 {

public static void main(String[] argv) throws Exception {
try {
Connection con = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/old","user","pass");
Connection con1 = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/new","user","pass");

String sql = "INSERT INTO users("+ "name,"+ "active,"+ "login,"+ "password)"+ "VALUES(?,?,?,?)";

Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);

PreparedStatement pstmt = con1.prepareStatement(sql);

ResultSet rs = statement.executeQuery("SELECT * FROM users");
while (rs.next()) {
String nm = rs.getString(2);
Boolean ac = rs.getBoolean(3);
String log = rs.getString(4);
String pass = rs.getString(5);

pstmt.setString(1, nm);
pstmt.setBoolean(2, ac);
pstmt.setString(3, log);
pstmt.setString(4, pass);

pstmt.executeUpdate();
}
} catch (SQLException e) {
System.out.println("could not get JDBC connection: " +e);
} finally {
con.close();
con1.close();
}
}

}

关于java - JDBC程序从一个表中选择数据并插入到不同数据库中的另一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13547276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com