So I need to to take data from a Varray I created on Oracle with java program. If someone knows. I tried this
My VArray.
CREATE OR REPLACE TYPE cancion IS VARRAY(13) of VARCHAR2(20);/
My function in java.
private ArrayList<String> getCanciones(int codDisco) {
this.open();//open connection
ArrayList<String> x = new ArrayList<String>();
String util;
String sql = "SELECT canciones from TDisco where codDisco = "+codDisco;
try {
PreparedStatement select = con.prepareStatement(sql);
System.out.println(sql);
ResultSet rs = select.executeQuery(sql);
while(rs.next()){
util=rs.getString(1);
x.add(util);
};
} catch (SQLException e) {
e.printStackTrace();
}
this.close();//close connection
return x;
}
Using a simple array doesn´t give problems to take all the data. So I just do it this way and working fine.
private ArrayList<String> getCanciones(int codDisco) {
// TODO Auto-generated method stub
ArrayList<String> x=new ArrayList<String>();
String[] values = null;
ARRAY array;
String sql = "SELECT canciones from TDisco where codDisco = "+codDisco;
try {
PreparedStatement select = con.prepareStatement(sql);
System.out.println(sql);
ResultSet rs = select.executeQuery(sql);
while(rs.next()){
array = (ARRAY) rs.getArray(1);
values = (String[]) array.getArray();
};
} catch (SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < values.length; i++) {
x.add(values[i]);
}
return x;
}
Related
I'm using a MySQL database to hold information for my reminder application in Java. I'm trying to pull the information out and store it in an array and the compare each element of the array to an updating current timestamp. The issue is the code I have gives a nullpointer exception and I can't figure out why. It works when the LocalDateTime isn't an array but the moment I turn it into an array it throws the error. It also demands I initialize it to null over anything else.
Thoughts on how I can fix this? Any help is appreciated.
Here's the method in question.
public static LocalDateTime[] getReminderTime()
{
String SQL = "SELECT r_dateTime FROM reminder_database.reminder;";
LocalDateTime reminderTime[] = null;
try
{
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
if(rs.isBeforeFirst())
{
for(int i = 0; rs.next(); i++)
{
reminderTime[i] = rs.getTimestamp(1).toLocalDateTime();
}
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Exception thrown with getReminderTime --> " + e + e.getStackTrace());
}
return reminderTime;
}
Heres the exception thrown
Exception thrown with getReminderTime --> java.lang.NullPointerException[Ljava.lang.StackTraceElement;#6dfc1e5f
Exception thrown with getReminderTime --> java.lang.NullPointerException[Ljava.lang.StackTraceElement;#3b2da18f
Found a solution.
I needed to initialize a size for the array in order to fill it. So I created another method that went through all the elements and gets the size.
Here's the code.
public static LocalDateTime[] getReminderTime()
{
String SQL = "SELECT r_dateTime FROM reminder_database.reminder;";
LocalDateTime reminderTime[] = null;
reminderTime = new LocalDateTime[getSizeOfRs()];
try
{
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
if(rs.isBeforeFirst())
{
for(int i = 0; rs.next(); i++)
{
reminderTime[i] = rs.getTimestamp(1).toLocalDateTime();
}
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Exception thrown with getReminderTime --> " + e + e.getStackTrace());
}
return reminderTime;
}
and the get rs size
public static int getSizeOfRs()
{
String SQL = "SELECT * FROM reminder_database.reminder;";
int size = 0;
try {
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
for(int i = 0; rs.next(); i++)
size++;
}
catch(Exception e)
{
System.out.println("Exception thrown with getSizeofRS --> " + e + e.getStackTrace());
}
return size;
}
I have a method that takes a database connection, query, and parameters and parses that query into a result set object. This is great but the problem is to get each value out of a result set I have to write one line of code for every row of data I am pulling to then save it in a JSON container. Is there a way to do this systematically so I can automatically parse the data type and create the JSON object based upon the keys fetched from the result set w/o manually specifying the keys?
public static JSONArray q2rs2j(Connection connection, String query, List<String> params) throws Exception {
JSONArray tContainer = new JSONArray();
PreparedStatement pStatement = connection.prepareStatement(query);
int pit = 1;
if(params != null) {
for (String param : params) {
try {
double paramAsDouble = Double.parseDouble(param);
try {
int paramAsInt = Integer.parseInt(param);
pStatement.setInt(pit, paramAsInt);
} catch (NumberFormatException e) {
pStatement.setDouble(pit, paramAsDouble);
}
} catch (NumberFormatException e) {
pStatement.setString(pit, param);
}
pit++;
}
}
ResultSet resultSet = pStatement.executeQuery();
try {
while (resultSet.next()) {
// Iterate through KEYS in the resultSet.next() row
while (hasKey) {
// Store key Name and key Value in variables - todo: determine data type via try parsing as Int, double, etc
String thisKeyName = (nextKeyName);
String thisKeyValue = (nextKeyValue);
JSONObject tObject = new JSONObject();
tObject
.put(nextKeyName, nextKeyValue);
}
tContainer.put(tObject);
}
resultSet.close();
} catch (Exception e) { e.printStackTrace(); }
return tContainer;
}
ResultSetMetaData provides SQL types and java class names.
try (ResultSet resultSet = pStatement.executeQuery()) {
ResultSetMetaData meta = resultSet.getMetaData();
int ncols = meta.getColumnCount();
while (resultSet.next()) {
JSONObject tObject = new JSONObject();
for (int colno = 1; colno <= ncols; ++colno) {
String label = meta.getColumnLabel(colno); // Key
String name = meta.getColumnName(colno);
String sqlType = meta.getColumnType();
String type = meta.getColumnClassName();
String thisKeyName = label;
Object thisKeyValue = result.getObject(colno);
if (sqlType.contains("CHAR")) {
thisKeyVaule = result.getString(colno);
tObject.put(nextKeyName, nextKeyValue);
} else if (sqlType.contains("INT")) {
thisKeyVaule = result.getInt(colno);
tObject.put(nextKeyName, nextKeyValue);
} else {
tObject.put(nextKeyName, nextKeyValue);
}
}
tContainer.put(tObject);
}
}
Using try-with-resources allows automatic closing (useful for Connection, Statement, and ResultSet) - even when on return, break or thrown exception.
I have a database table with columns : name, residence, contact. and I want to retrieve only the values in the 'contact column' into an array. the following code is what I wrote:
List l = new ArrayList();
try {
String sql = "select * from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String con = rs.getString("Contact");
l.add(con);
System.out.println(l);
}
} catch (Exception e) {
e.getMessage();
}
but this generates the following result:
[0547615632]
[0547615632, 0246687643]
[0547615632, 0246687643, 0558581764]
whilst I have only 3 records in the table and each having a contact value.
please how do I write the code so that I can get only a single array displaying the result like this:
[0547615632, 0246687643, 0558581764]
thank you very much.
You should move the print command out of the while loop:
List l = new ArrayList();
try {
String sql = "select * from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String con = rs.getString("Contact");
l.add(con);
}
} catch (Exception e) {
e.getMessage();
}
System.out.println(l);
OR only print the current element in each iteration;
List l = new ArrayList();
try {
String sql = "select * from members";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String con = rs.getString("Contact");
l.add(con);
System.out.print(con + " ");
}
} catch (Exception e) {
e.getMessage();
}
I am running a query on ID column but I don't want it to be visible in my frame/pane. How can I achieve this? Shall I make another table, is there a function in sql/mysql which allows to hide columns? I tried to google it but havent found anything yet.
Here is the code:
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
Connection connection = TableWithBottomLine.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
connection.setAutoCommit(false);
stmt = connection.createStatement();
stmt.addBatch("update finance.fin set " + stulpPav + " = " + duom
+ " where ID = " + studId + ";");
stmt.executeBatch();
connection.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
connection.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
int rowCount;
Object data [][];
String columnNames [];
public MyTableModel() throws SQLException{
String query ="SELECT ID, tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport, Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
ResultSet rs ;
Connection connection = TableWithBottomLine.getConnection();
Statement stmt = null;
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][11];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getInt("ID");
data[iEil][1] = rs.getDate("Date");
data[iEil][2] = rs.getFloat("Flat");
data[iEil][3] = rs.getFloat("Mobile");
data[iEil][4] = rs.getFloat("Food");
data[iEil][5] = rs.getFloat("Alcohol");
data[iEil][6] = rs.getFloat("Transport");
data[iEil][7] = rs.getFloat("Outdoor");
data[iEil][8] = rs.getFloat("Pauls_stuff");
data[iEil][9] = rs.getFloat("Income");
data[iEil][10] = rs.getFloat("Stuff");
}
String[] columnName = {"ID", "Date","Flat","Mobile"
,"Food","Alcohol","Transport", "Outdoor", "Pauls_stuff", "Income", "Stuff"};
columnNames = columnName;
}
This has solved my problem:
table.removeColumn(table.getColumnModel().getColumn(0));
I placed this in my class contructor. This lets remove the column from the view of the table but column 'ID' is still contained in the TableModel. I found that many people looking for an option to exclude specific column (like autoincrement) from SELECT statement in sql / mysql but the language itself doesn't have that feature. So I hope this solution will help others as well.
Don't put ID in the select part of the query
String query ="SELECT tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport,
Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
I have an excel spreadsheet with data in just the first 2 columns. I want to sort the data into an array so that I can loop through and perform calculations with the data.
So far, I've been able to just output the content of the spreadsheet to the console log. I am very new to Java programming and I need help.
This the code I have thus far:
import java.sql.*;
import java.util.*;
public class testJDBC {
public static void main(String[] args) {
//private static List<DataItem> myList = ArrayList<DataItem>();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Sample_Defects");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select * from [Sheet1$]");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while (rs.next()) {
//DataItem d = new DataItem();
// d.setID(rs.getString(1));
// d.setSTATUS(rs.getString(2));
//myList.add(d);
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) System.out.print(" , " );
String columnValue = rs.getString(i);
System.out.print(columnValue);
}
System.out.println();
}
st.close();
con.close();
} catch (Exception ex) {
System.err.print("Exception: ");
System.err.println(ex.getMessage());
}
}
}
You can insert the data in a 2D array. and then sort it.
Something like - String[][] array = new String[2][numberOfColumns];
Then you can use the Arrays.sort() method to sort. you can also override the method to get your desired sorting like -
Arrays.sort(array, new Comparator<String[]>() {
public int compare(String[] a, String[] b) {
return a[0].compareTo(b[0]);
}
});