Skip to content

Instantly share code, notes, and snippets.

@pablohdzvizcarra
Created July 14, 2021 14:37
Show Gist options
  • Save pablohdzvizcarra/fec3f3f64b28b366fc3c1e01b78ec6c6 to your computer and use it in GitHub Desktop.
Save pablohdzvizcarra/fec3f3f64b28b366fc3c1e01b78ec6c6 to your computer and use it in GitHub Desktop.
create a file with data form the database and read the data
package com.pluralsight.jdbc.course.m7c3;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import java.io.*;
import java.sql.SQLException;
public class RowSet
{
public static void main(String[] args)
{
String status = "In Process";
try (CachedRowSet rowSet = ordersByStatus(status);
FileOutputStream fout = new FileOutputStream("src/main/resources/row.ser");
ObjectOutputStream oss = new ObjectOutputStream(fout))
{
oss.writeObject(rowSet);
try(FileInputStream fin = new FileInputStream("src/main/resources/row.ser");
ObjectInputStream ois = new ObjectInputStream(fin);
CachedRowSet rowSet1 = (CachedRowSet) ois.readObject())
{
while (rowSet1.next())
{
int customerOrder = rowSet1.getInt("customerNumber");
int orderNumber = rowSet1.getInt("orderNumber");
System.out.println(customerOrder + " " + orderNumber + " " + status);
}
}
} catch (SQLException | IOException | ClassNotFoundException throwables)
{
throwables.printStackTrace();
}
}
public static CachedRowSet ordersByStatus(String status) throws SQLException
{
String query = "SELECT * FROM orders WHERE status=?";
RowSetFactory rowSetProvider = RowSetProvider.newFactory();
CachedRowSet cachedRowSet = rowSetProvider.createCachedRowSet();
cachedRowSet.setUrl("jdbc:mysql://localhost:3306/classicmodels?user=root&" +
"password=my-secret-pw&serverTimezone=UTC");
cachedRowSet.setCommand(query);
cachedRowSet.setString(1, status);
cachedRowSet.execute();
return cachedRowSet;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment