Inserting into MySQL Table

Here’s how to get result from a table using ResultSet and use it as variables to be inserted to another table using PreparedStatement


import java.sql.*;
import java.sql.DriverManager;
import java.sql.Connection;
import com.mysql.jdbc.Driver;
import java.net.*;
import java.io.*;
public class CountUser{
public static void main(String args[]) {
try{
Class.forName("com.mysql.jdbc.Driver");
// Connection connection = DriverManager.getConnection("jdbc:mysql://167.205.24.50/table","root","");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/table","root","");
Statement st1 = connection.createStatement();
Statement st2 = connection.createStatement();

ResultSet rs1 = st1.executeQuery("SELECT * FROM user");

while (rs1.next()) {
java.sql.Date date = rs1.getDate(5);
String strDate = date.toString();

PreparedStatement ps = connection.prepareStatement("INSERT INTO count_temp (no, date) VALUES (?,?)");
ps.setInt(1, i);
ps.setString(2, strDate);
ps.executeUpdate();
}
}
catch (Exception e){
System.out.println("Error: " + e);
}
}
}
Advertisements