Fail to convert to internal representation JDBC - java

Ok so this is my code
public static ArrayList getMaterialerFraOrdreNr(String s_date, String e_date) throws SQLException, InterruptedException {
int tal = 0;
ArrayList nameOfColumns = getNameOfColumns(); // name of columns
ArrayList orderNumber = getOrdre_Nr_FromDB(s_date, e_date); // order number
//første loop kører gennem number of columns
//anden loop kører gennem name of column
ResultSet rs = null;
Connection con = null;
try {
Class.forName(DB.driver);
con = DriverManager.getConnection(DB.URL, DB.ID, DB.PW);
for (int i = 1; i < orderNumber.size(); i++) {
for (int j = 1; j < nameOfColumns.size(); j++) {
String nameOfColum = (String) nameOfColumns.get(i);
int orderNr = (Integer) orderNumber.get(j);
System.out.println("orderNr " + orderNr);
//SELECT v1001 FROM ORDRE_spec WHERE ordre_nr = 1;
String query = "SELECT ? AS ans FROM ordre_spec WHERE ordre_nr = ?";
PreparedStatement prest = con.prepareStatement(query);
prest.setString(1, nameOfColum);
prest.setInt(2, orderNr);
System.out.println("orderNr " + orderNr);
System.out.println("nameOfColum = " + nameOfColum);
rs = prest.executeQuery();
if(rs.next()){
tal = rs.getInt("ans");
MaterialeNum.add(tal);
System.out.println("materiale num = " + MaterialeNum);
}
}
}
} catch (ClassNotFoundException | SQLException ee) {
System.out.println("fail og der er så her");
System.err.println(ee);
} finally {
con.close();
}
System.out.println(kundeNum.toString());
return kundeNum;
}
public static void main(String[] args) throws SQLException, InterruptedException {
NewClass.getMaterialerFraOrdreNr("1990-10-10", "2020-10-10");
}
And my problem is that I'm getting a java.sql.SQLException: Fail to convert to internal representation
I really cant see what the error should be.. plz help if you can see the error :)

String query = "SELECT ? AS ans FROM ordre_spec WHERE ordre_nr = ?";
You cannot parameterize column names. You can only parameterize column values.
Basically you need to do:
String query = "SELECT " + nameOfColum + " AS ans FROM ordre_spec WHERE ordre_nr = ?";
Keep in mind that this is prone to SQL injection if nameOfColum is controllable by enduser. If this is indeed the case, you may want to perform string matching on e.g. \w+ before continuing.

Related

Can't print output through loop, don't know how to print second table

Edit: anything would help. If anyone can tell me the process at least I'd appreciate it.
I'm trying to get my code to read for an access database that I made. In that database are 2 tables, one is Soccer_Team and the other is Soccer_Players. I'm having an issue figuring out how to have the field name show up in front of the actual data. When I run the code now I get this:
Name: Location: Home Stadium: FC Barcelona Spain Camp Nou
Name: Location: Home Stadium: FC Bayern Munich Germany Allianz
I want the "Name:" to be followed by the club name, and so on... I am not familiar with Java so I am a little confused here.
Also, I want to print the second table from my database through an SQL query, that has it display the above but with the player information printed under each row... I don't even know where to begin doing that. I'm not sure I'm explaining this well, so sorry if I'm confusing people.
Sorry if this is asking too much but I am pretty lost... Thanks for any help guys.
package msjavaaccessdb;
import java.sql.*;
import java.util.*;
public class MSjavaAccessDB {
/** Creates a new instance of databaseApplication */
public MSjavaAccessDB() {
}
/**
* #param args the command line arguments
*/
static String nameOfJdbcOdbcDriver =
"sun.jdbc.odbc.JdbcOdbcDriver";
// static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String userName = "";
static String passwordForUser = "";
static Connection myConnectionRequest = null;
static Statement myStatementObject = null;
static ResultSet myResultTuples = null;
static ResultSetMetaData myResultTuplesMetaData = null;
static String queryToBeExecuted = "select * from Soccer_Team";
public static void main(String args[])
throws ClassNotFoundException {
try {
//Identify the driver to use
Class.forName(nameOfJdbcOdbcDriver);
//Attempt a connection to database...
Connection myConnectionRequest =
DriverManager.getConnection(
dataBaseNameDSN, userName, passwordForUser);
//Create a statement object, use its method to execute query
Statement myStatementObject =
myConnectionRequest.createStatement();
//Use statement object method to execute a query.
//Hold results in a resutl set...like a cursor
ResultSet myResultTuples = myStatementObject.executeQuery
(queryToBeExecuted);
//Call metadata to get the number of attributes
myResultTuplesMetaData = myResultTuples.getMetaData();
int numberOfAttributes =
myResultTuplesMetaData.getColumnCount();
System.out.println(Integer.toString(numberOfAttributes));
//For each row in result set, print ALL columns
for(int rowNum = 1; myResultTuples.next(); rowNum++) {
for (int i = 1; i <= numberOfAttributes; i++) {
if ( (i != 1) ) System.out.print (
myResultTuples.getString(i) + "\t");
else {//String xyz = myResultTuples.getString(1);
int xyz = Integer.parseInt( myResultTuples.getString(1));
System.out.print ("Name: ");
System.out.print ("Location: ");
System.out.print ("Home Stadium: ");
}
}
System.out.println("\n\n");
}
} // end of try block
//handle ALL exceptions to above database calls
catch (SQLException sqlError) {
System.out.println("Unexpected exception : " +
sqlError.toString() + ", sqlstate = " +
sqlError.getSQLState());
sqlError.printStackTrace();
}
} // end of main method of this class
} // end of the class
So I don't know how your datatable looks, but what i guess you want to do is print the column label and then the corresponding data value of the row.
for(int rowNum = 1; myResultTuples.next(); rowNum++) {
for (int i = 1; i <= numberOfAttributes; i++) {
//print column label
System.out.print(myResultTuplesMetaData.getColumnLabel(i) + ": ");
//print data value
System.out.print(myResultTuples.getString(i) + "\t");
}
System.out.println("\n\n");
//process SQl-Query about players and print out results in another for loop HERE
}
So for the second table you would have to do sth like SELECT * FROM table2 WHERE team IS (?) as a PreparedStatement and print out the results in another loop.
I can't get the error right now because I don't have access to NetBeans at this moment. I can update later when I am on my home computer. I'm not sure if what I did makes sense, because I don't exactly know what the rules of Java are... Hope this isn't stroke inducing.
package msjavaaccessdb;
import java.sql.*;
import java.util.*;
public class MSjavaAccessDB {
/** Creates a new instance of databaseApplication */
public MSjavaAccessDB() {
}
/**
* #param args the command line arguments
*/
static String nameOfJdbcOdbcDriver =
"sun.jdbc.odbc.JdbcOdbcDriver";
static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String userName = "";
static String passwordForUser = "";
static Connection myConnectionRequest = null;
static Statement myStatementObject = null;
static ResultSet myResultTuples = null;
static ResultSetMetaData myResultTuplesMetaData = null;
static ResultSet ResultTuples = null;
static ResultSetMetaData ResultTuplesMetaData = null;
static String queryToBeExecuted = "select * from Soccer_Team";
static string secondQuery = "select * from Soccer_Player where team is (?)";
public static void main(String args[])
throws ClassNotFoundException {
try {
//Identify the driver to use
Class.forName(nameOfJdbcOdbcDriver);
//Attempt a connection to database...
Connection myConnectionRequest =
DriverManager.getConnection(
dataBaseNameDSN, userName, passwordForUser);
//Create a statement object, use its method to execute query
Statement myStatementObject =
myConnectionRequest.createStatement();
//Use statement object method to execute a query.
//Hold results in a resutl set...like a cursor
ResultSet myResultTuples = myStatementObject.executeQuery
(queryToBeExecuted);
ResultSet ResultTuples = myStatementObject.executeQuery
(secondQuery);
//Call metadata to get the number of attributes
myResultTuplesMetaData = myResultTuples.getMetaData();
int numberOfAttributes =
myResultTuplesMetaData.getColumnCount();
System.out.println(Integer.toString(numberOfAttributes));
ResultTuplesMetaData = ResultTuples.getMetaData();
int numOfAttributes =
ResultTuplesMetaData.getColumnCount();
System.out.println(Integer.toString(numOfAttributes));
//For each row in result set, print ALL columns
for(int rowNum = 1; myResultTuples.next(); rowNum++) {
for (int i = 1; i <= numberOfAttributes; i++) {
//print column label
System.out.print(myResultTuplesMetaData.getColumnLabel(i) + ": ");
//print data value
System.out.print(myResultTuples.getString(i) + "\t");
}
System.out.println("\n\n");
}
for(int rowNum = 1; ResultTuples.next(); rowNum++) {
for (int i = 1; i <= numOfAttributes; i++) {
//print column label
System.out.print(ResultTuplesMetaData.getColumnLabel(i) + ": ");
//print data value
System.out.print(ResultTuples.getString(i) + "\t");
}
System.out.println("\n\n");
}
} // end of try block
//handle ALL exceptions to above database calls
catch (SQLException sqlError) {
System.out.println("Unexpected exception : " +
sqlError.toString() + ", sqlstate = " +
sqlError.getSQLState());
sqlError.printStackTrace();
}
} // end of main method of this class
} // end of the class

jdbc Mysql nested resultset

See Below. rs.getString("tags") is subquery with more than 1 row. I want to iterate that subquery(rs.getString("tags") ---- Like rs.next().
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("id"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
while(rs.getString("tags").next()){
arrtags[i] = rs.getString(1);
}
emaildto.setTags(arrtags);
rs.getString("tags") does not work --- and contain more than 1 rows. How to extract it. Is there any technique?
Try something like this:
Array tagsArray = rs.getArray("tags");
String[] tags = (String[])tagsArray.getArray();
this is not answer. this is complete code
List emails = new ArrayList();
String listQuery = "select mid, sub, message, "
+ " (select emailid from sub_ids where sub_ids.messageid= sub_mail_list.mid ) // this query fetch more than one row.
as refid"
+ " from sub_mail_list";
PreparedStatement ps = null;
ResultSet rs;
try {
ps = DatabaseConnectionUtil.getConnection().prepareStatement(
listQuery);
rs = ps.executeQuery(listQuery);
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("mid"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
Array tagsArray = rs.getArray("refid");
List<vtbDto> vtbdtosvr = new ArrayList<vtbDto>();
int[] tags = (int[])tagsArray.getArray();
for (int i = 0; i < tags.length; i++) {
vtbDto vtbdto = new vtbDto();
vtbdto.setRefid(tags[i]);
vtbdtosvr.add(vtbdto);
}
emaildto.setAr(tagsArray);
emails.add(emaildto);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
DatabaseConnectionUtil.closeAll(ps);
}
return emails;
And this is code to print function
List emailDtos = emaildao.getAllemails();
for (emailDto emailDto2 : emailDtos) {
System.out.println( emailDto2.getMid());
System.out.println( emailDto2.getSub());
System.out.println( emailDto2.getMessage());
List<vtbDto> vtbdtos= emailDto2.getVtbdtolst();
for (vtbDto vtbdto2 : vtbdtos) {
System.out.print(vtbdto2.getRefid() + ", ");
}
}
and the console print "Subquery returns more than 1 row";

Search a JTable using multiple JTextfield

I have a JFrame that has 3 JTextfields and 2 JDatechooser, what I am trying to do is if only one JTextfield has something typed in it and I press the search button, then I will be able to retrieve the data to JTable, but the problem is I have to fill out all JTextFileds and JDatechooser in order to retrieve data. My idea is to ignore null JTextfields and JTdatechooser if only one JTextfield has the keyword I want ?? Any suggestions ?? Thanks in advance,
public ArrayList<BillsRecord> getBillRecordByID(int EmpCode, String Fname, String Lname, String sDate, String eDate) throws SQLException {
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE B.EMP_ID = ? "
+ " OR E.FNAME = ? "
+ " OR E.LNAME = ? "
+ " OR DATE BETWEEN ? AND ? "
+ " ORDER BY B.DATE";
DBConnection con = new DBConnection();
Connection connect = con.getConnection();
PreparedStatement ps = null;
ArrayList<BillsRecord> records = new ArrayList<>();
try {
ps = connect.prepareStatement(sql);
ps.setInt(1, EmpCode);
ps.setString(2, Fname);
ps.setString(3, Lname);
ps.setString(4, sDate);
ps.setString(5, eDate);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
BillsRecord billrec = new BillsRecord();
billrec.setDATE(rs.getString("DT"));
billrec.setEMP_ID(rs.getInt("EMP_ID"));
billrec.setFNAME(rs.getString("FNAME"));
billrec.setLNAME(rs.getString("LNAME"));
billrec.setMONEY_SENT(rs.getDouble("MONEY_SENT"));
billrec.setRENT(rs.getDouble("RENT"));
billrec.setPHONE(rs.getDouble("PHONE"));
billrec.setGAS(rs.getDouble("GAS"));
billrec.setELECTRICITY(rs.getDouble("ELECTRICITY"));
billrec.setINTERNET(rs.getDouble("INTERNET"));
billrec.setOTHER(rs.getDouble("OTHER"));
records.add(billrec);
return records;
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
if (ps != null) {
ps.close();
}
if (connect != null) {
connect.close();
}
}
return null;
}
private void search() {
try {
JTextField stxt = ((JTextField) startdatetxt.getDateEditor().getUiComponent());
String sDATE = stxt.getText().trim();
JTextField etxt = ((JTextField) enddatetxt.getDateEditor().getUiComponent());
String eDATE = etxt.getText().trim();
int EMP_ID = Integer.parseInt(this.empidtxt.getText().trim());
String FNAME = this.firstnametxt.getText().trim();
String LNAME = this.lastnametxt.getText().trim();
BillRecordDao billrecdao = new BillRecordDao();
ArrayList<BillsRecord> records = billrecdao.getBillRecordByID(EMP_ID, FNAME, LNAME, sDATE, eDATE);
Object[] tableColumnName = new Object[11];
tableColumnName[0] = "Date";
tableColumnName[1] = "H.License";
tableColumnName[2] = "First Name";
tableColumnName[3] = "Last Name";
tableColumnName[4] = "MONEY SENT";
tableColumnName[5] = "RENT";
tableColumnName[6] = "PHONE";
tableColumnName[7] = "GASE";
tableColumnName[8] = "ELECTRICITY";
tableColumnName[9] = "INTERNET";
tableColumnName[10] = "OTHER";
DefaultTableModel tbd = new DefaultTableModel();
tbd.setColumnIdentifiers(tableColumnName);
this.BillsSummaryTable.setModel(tbd);
Object[] RowRec = new Object[11];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
RowRec[1] = records.get(i).getEMP_ID();
RowRec[2] = records.get(i).getFNAME().toUpperCase();
RowRec[3] = records.get(i).getLNAME().toUpperCase();
RowRec[4] = records.get(i).getMONEY_SENT();
RowRec[5] = records.get(i).getRENT();
RowRec[6] = records.get(i).getPHONE();
RowRec[7] = records.get(i).getGAS();
RowRec[8] = records.get(i).getELECTRICITY();
RowRec[9] = records.get(i).getINTERNET();
RowRec[10] = records.get(i).getOTHER();
tbd.addRow(RowRec);
}
} catch (SQLException e) {
System.out.println(e.toString());
}
}
Basically, you need to create a variable/dynamic query based on the available values
Now, you can do this using something like StringBuilder or even storing each query element in a List or array, but you always end up with the "trailing OR" problem (you need to know when you've got to the last element and not append the "OR" to the String or remove the trailing "OR" from the resulting String). While not difficult, it's just a pain.
However, if you're using Java 8, you can use StringJoiner!
StringJoiner sj = new StringJoiner(" OR ");
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE ";
List values = new ArrayList();
// EmpCode MUST be a Integer, so it can be null
if (EmpCode != null) {
sj.add("B.EMP_ID = ?");
values.add(EmpCode);
}
if (FName != null) {
sj.add("E.FNAME = ?");
values.add(FName);
}
if (LName != null) {
sj.add("E.LNAME = ?");
values.add(LName);
}
if (sDate != null && eDate != null) {
sj.add("DATE BETWEEN ? AND ?");
values.add(sDate);
values.add(eDate);
}
sql += sj.toString();
Connection connect = null;
try (PreparedStatement ps = connect.prepareStatement(sql)) {
for (int index = 0; index < values.size(); index++) {
ps.setObject(index + 1, values.get(index));
}
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
//...
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
You might also like to have a look at The try-with-resources Statement and have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Display nth highest value if matched with comboBox value

I am using cosine similarity function to compare the value between user input and the data in SQL. The highest value will be retrieved and displayed.
However, k is the value getting from comboBox and it is hard constraints which mean they need to be fulfilled. So I have set it to something like:
The highest value found in index X . Before display, it will check whether day is equal to k. If not, it will look at the second highest and so on until day is equal to k.
But this doesn't make sense at all. If day is equal to k only when it is in the ninth highest value, then I need to set until ninth highest value? Is there any method can solve this?
private void pick_highest_value_here_and_display(ArrayList<Double> value,
int k) throws Exception {
// TODO Auto-generated method stub
double aa[] = value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest = Double.MIN_VALUE;
double secHighest = Double.MIN_VALUE;
int highestIndex = 0;
for (int i = 0; i < aa.length; i++) {
if (aa[i] > highest) {
highest = aa[i];
highestIndex = i;
}
}
System.out.println("The highest value is " + highest + "");
System.out.println("It is found at index " + highestIndex + "");
String sql = "Select Day from menu where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int aaa = rs.getInt("Day");
System.out.println(aaa);
if (aaa == k) // check whether aaa(day) is equal to k (comboBox)
{
String sql1 = "Select * from placeseen where ID =?";
DatabaseConnection db1 = new DatabaseConnection();
Connection conn1 = db1.getConnection();
PreparedStatement ps1 = conn1.prepareStatement(sql1);
ps1.setInt(1, highestIndex);
ResultSet rs1 = ps1.executeQuery();
if (rs1.next()) {
String a = rs1.getString("place1");
String bbb = rs1.getString("place2");
Tourism to = new Tourism();
to.setPlace1(a);
to.setPlace2(bbb);
DispDay dc = new DispDay();
dc.setVisible(true);
}
ps1.close();
rs1.close();
conn1.close();
} else // if not equal
{
int secIndex = 0;
for (int i = 0; i < aa.length; i++) {
if (aa[i] > secHighest) {
secHighest = aa[i];
secIndex = i;
}
}
System.out.println("The second highest value is " + secHighest + "");
System.out.println("It is found at index " + secIndex + "");
String sql2 = "Select Day from menu where ID =?";
DatabaseConnection db2 = new DatabaseConnection();
Connection conn2 = db2.getConnection();
PreparedStatement ps2 = conn.prepareStatement(sql2);
ps2.setInt(1, secIndex);
ResultSet rs2 = ps.executeQuery();
if (rs2.next()) {
int de = rs2.getInt("Day");
System.out.println(de);
if (de == k) {
String l = "Select * from placeseen where ID =?";
DatabaseConnection db3 = new DatabaseConnection();
Connection conn3 = db3.getConnection();
PreparedStatement ps3 = conn3.prepareStatement(l);
ps3.setInt(1, secIndex);
ResultSet rs3 = ps3.executeQuery();
if (rs3.next()) {
String a = rs3.getString("place1");
String bbb = rs3.getString("place2");
Tourism to = new Tourism();
to.setPlace1(a);
to.setPlace2(bbb);
DispDay dc = new DispDay();
dc.setVisible(true);
}
ps3.close();
rs3.close();
conn3.close();
}
}
}
ps.close();
rs.close();
conn.close();
}
}
Your code is somewhat difficult to understand, bit it sounds like you are trying to obtain the "highest" database value (in some sense) whose value matching some user input.
At the most basic level, consider constructing a basic query that looks like:
SELECT MAX(value column)
FROM menu
JOIN placeseen
ON (conditions)
WHERE (condition to ensure that data matches input)
If that's possible, it's a high-performance way to ensure that the data lines up between the tables and also matches the user input.

how to get all tables and Their's columns of a specific schema using Java?

I have a database schema that its name is "Navid"
there is many tables in this schema.
definitely each table, has some columns.
what I need is a java class that:
Connect to my database.
Have a method that loop on all tables
2-1. Have an inner loop to define all columns of the table.
Make create table query statement .(I want to create the same table in another database).
Execute that query.
I write some code but I do not know what to do next.
public class automateExport {
static String value;
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// ResultSet rs = null;
String table_name;
String column_name;
String tableName = null;
StringBuilder sb = new StringBuilder(1024);
Connection DB2 = getConnection();
String sql = "SELECT TABSCHEMA,TABNAME,COLNAME FROM SYSCAT.COLUMNS WHERE TABSCHEMA NOT LIKE 'SYS%'";
PreparedStatement mainStmt = DB2.prepareStatement(sql);
ResultSet rs = mainStmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
/* while(rs.next()){
table_name = rs.getString(2);
// for(int i = 1; i <= 1; i ++){
column_name = rs.getString(3);
System.out.println("SSS::::: " + table_name + " " + column_name );
// }
*/
for (int i = 1; i <= rows; i++) {
while (rs.next()) {
table_name = rs.getString(2);
if (i > 1) {
sb.append(", ");
}
column_name = rs.getString(3);
String columnType = rsmd.getColumnTypeName(i);
sb.append(" ").append(column_name).append(" ").append(columnType);
int precision = rsmd.getPrecision(i);
if (precision != 0) {
sb.append("( ").append(precision).append(" )");
}
} // for columns
sb.append(" ) ");
String sql2 = sb.toString();
PreparedStatement m = DB2.prepareStatement(sql);
m.executeQuery();
System.out.println(sb.toString());
}
}
private static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("COM.ibm.db2os390.sqlj.jdbc.DB2SQLJDriver");
Connection connection
= DriverManager.getConnection("jdbc:db2://localhost:50000/navid", "navid", "oracle");
return connection;
}
}

Categories