Java strange variable assignment enquiry - java

I've come across a weird situation. The code is as below:
public static int add(String trcd, String tlcd, String dept, String doDate,
String doTime, String andConfirm, Teller admin) throws
Exception {
try {
String table1 = "table1";
String table2 = "table2";
String trap = null;
String trtype = null;
String sql = "select * from " + table2;
DataSet dataset = DBOper.DBQuery("taUtil", sql);
if (dataset.isEmpty()) {
return -1;
}
else {
HashMap map = dataset.getRow(0);
trap = (String) map.get("aut_ap_code");
trtype = (String) map.get("aut_type_code");
//point 1
sql = "insert into " + table1 + " values("+trtype + "','" + doDate + "','" + doTime + "','N','Y')";
DBOper.DBUpdate("taUtil", sql);
if (andConfirm.equals("Y")) {
//point 2
sql = "select * " + table1 +" where tr_create_date='" + doDate + "' and tr_create_time='" + doTime + "' and tr_stcd='Y'";
//point 3
DataSet dataset2 = DBOper.DBQuery("taUtil", sql);
if (dataset2.isEmpty()) {
return -2;
}
else {
String trNo = null;
HashMap map2 = dataset2.getRow(0);
trNo = (String) map2.get("tr_no");
confirm(admin, trNo, "N");
}
}
return 0;
}
}
catch (Exception e) {
throw e;
}
}
The problem is:
at point 3, it
always prints "insert" ie the previous sql value instead of the latest assignment of "select".
Does anybody knows why is it so ?
Thanks

You have a syntax error in your assignment statement:
sql = "insert into " + table1 + " values(trtype + "','" + doDate + "','" + doTime + "','N','Y')";
Try to replace it with:
sql = "insert into " + table1 + " values(" +trtype + "',' " + doDate + "','" + doTime + "','N','Y')";
I'm not sure how you even managed to compile this...
EDIT: If this syntax error does stop the code from compiling and your IDE (assuming you are using one) executes older version of the class that could not be compiled (has happened to me using Eclipse on occasions), I think it could end up doing something completely unpredictable and possibly explain this odd behavior.

Related

Java [SQLITE_ERROR] SQL error or missing database (near "resi": syntax error)

i have some issues when i'm run the program. It says "[SQLITE_ERROR] SQL error or missing database (near "resi": syntax error)" and "ada yang salah:java.sql.SQLException: ResultSet is TYPE_FORWARD_ONLY". Am i passed something or what?
connection code
public void koneksiDatabase(){
try{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:C:/Users/sqlite3/cekresi.db","root","");
System.out.println("Koneksi berhasil!");
}catch(ClassNotFoundException eclass){
System.out.println("Koneksi Gagal!");
}catch(SQLException esql){
System.out.println(esql.getMessage());
}
}
savedata code
public void simpanData(){
try {
String sql = "Insert into data resi = \"" + txtResi.getText() + "\","
+ "nama = \"" + txtNama.getText() + "\","
+ "tujuan = \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ "tarif = \"" + txtTarif.getText() + "\","
+ "berat = \"" + txtBerat.getText() + "\","
+ "jumlah = \"" + txtJumlah.getText() + "\"";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
System.out.println("berhasil!");
}catch (Exception e){
System.out.println(e);
}
tampilDataKeTabel();
}
showtable code
public void tampilDataKeTabel(){
ResultSet rs = null;
try{
Statement stmt = con.createStatement();
rs = stmt.executeQuery("select * from data");
ResultSetMetaData meta = rs.getMetaData();
int col = meta.getColumnCount();
int baris = 0;
while (rs.next()){
baris = rs.getRow();
}
dataTable = new String[baris][col];
int x = 0;
rs.beforeFirst();
while(rs.next()){
dataTable[x][0] = rs.getString("resi");
dataTable[x][1] = rs.getString("nama");
dataTable[x][2] = rs.getString("tujuan");
dataTable[x][3] = rs.getString("tarif");
dataTable[x][4] = rs.getString("berat");
dataTable[x][5] = rs.getString("jumlah");
x++;
}
tabelDisplay.setModel(new DefaultTableModel(dataTable,header));
}catch(Exception e){
System.err.println("ada yang salah:"+e);
}
}
There are syntax issues in the insert statement. The syntax should be:
INSERT INTO table (column1,column2 ,..)
VALUES( value1, value2 ,...);
So your insert statement should be something like:
String sql = "Insert into data(resi,nama,tujuan,tarif,berat,jumlah)
values(\"" + txtResi.getText() + "\","
+ \"" + txtNama.getText() + "\","
+ \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ \"" + txtTarif.getText() + "\","
+ \"" + txtBerat.getText() + "\","
+ \"" + txtJumlah.getText() + "\")";
Also, there is an issue in the code to show the data.
while (rs.next()){
baris = rs.getRow();
}
This loop is traversing the result set once. So the next loop would fail as rs has already reached the end of results.
This is causing the exception : ResultSet is TYPE_FORWARD_ONLY
Instead of creating a 2D string array, Create a class corresponding to your db table and then create a List. Assuming a class named Data would be created, the second while loop would be :
List<Data> dataList = new ArrayList<>();
while(rs.next()){
Data data = new Data();
data.setResi(rs.getString("resi"));
data.setNama(rs.getString("nama"));
data.setTujuan(rs.getString("tujuan"));
data.setTarif(rs.getString("tarif"));
data.setBerat(rs.getString("berat"));
data.setJumlah(rs.getString("jumlah"));
dataList.add(data);
}

Try with resource class variable gets null

protected void saveData() {
Map<String, String> allStationsParams = new HashMap<>();
List<String> stations = getAllStations();
stmt = Database.getUpdateableStatement();
today = (SysTime.currentTimeMillis() / DasStamp.TICKS_PER_DAY) *
DasStamp.TICKS_PER_DAY;
String changeTimestamp = DasStamp.asCompactString(today);
String keyName = "COM.MAPPINGTOOLTIP." + attributeValue;
for (int row = 0; row < this.getTableModel().getRowCount(); row++) {
String station = (String)this.getTableModel().getValueAt(row, 0);
putInStationParams(this, station, allStationsParams, row);
}
for (String station : stations) {
boolean sendToDB = false;
try (ResultSet rs = this.rsParameters) {
rs.beforeFirst();
while (rs.next()) {
if (rs.getString("station").equals(station)) {
sendToDB = true;
break;
}
}
if (sendToDB) {
if (!rs.getString("value_text").equals(allStationsParams.get(station)) || !allStationsParams.containsKey(station)) {
sendToDB = true;
} else {
sendToDB = false;
}
} else if (allStationsParams.containsKey(station)) {
sendToDB = true;
}
if (sendToDB) {
String sql = "REPLACE INTO dss_parameter (key_name, station, valid_from, value_text"
+ ", change_timestamp) VALUES ('"
+ keyName + "','" + station + "','" + DasStamp.asDateOnlyString(today) + "','"
+ Helper.nz(allStationsParams.get(station)) + "','"
+ changeTimestamp + "') ;";
if (null != stmt) {
stmt.execute(sql);
if (!isResultSetEmpty(rs) && !rs.isAfterLast()) {
AdminLogger.log("dss_parameter", Action.UPDATE,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"value_text='" + rs.getString("value_text") + "'",
"value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
} else {
AdminLogger.log("dss_parameter", Action.INSERT,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"", "value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
}
}
}
} catch (SQLException e) {
AppFrame.msgBox("Error on insert: " + e.getMessage());
Helper.printMessage(true, false, "Parameter save failed!!", e);
}
}
}
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
Your rsParameters parameter is of Type Resultset.
In first iteration, after try{} block is complete close() method of rsParameters:ResultSet is called.
This internally makes all the properties of resultSet NUll.
That is the reason for getting Null properties during second iteration.
SEE: http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.27/com/mysql/jdbc/ResultSetImpl.java#ResultSetImpl.realClose%28boolean%29

Trouble Updating a Table Row in Java

Connection conn = SqlConnection.getConnection("jdbc:mysql://localhost:3306/stocks");
Statement statement = conn.createStatement();
File path = new File("/Users/Zack/Desktop/JavaDB/BALANCESHEETS");
for(File file: path.listFiles()) {
if (file.isFile()) {
String fileName = file.getName();
String ticker = fileName.split("\\_")[0];
if (ticker.equals("ASB") || ticker.equals("FRC")) {
if (ticker.equals("ASB")) {
ticker = ticker + "PRD";
}
if (ticker.equals("FRC")) {
ticker = ticker + "PRD";
}
}
//CSVReader reader = new CSVReader(new FileReader(file));
//List entries = reader.readAll();
//ArrayList<String> entry = new ArrayList<String>();
Reader reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
String string = builder.toString();
ArrayList<String> stringResult = new ArrayList<String>();
if (string != null) {
String[] splitData = string.split("\\s*,\\s*|\\n");
for (int i = 0; i <splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() ==0)) {
stringResult.add(splitData[i].trim());
}
}
}
String columnName = null;
int yearCount = 0;
for (int i = 0; i < stringResult.size(); i++) {
int sL = stringResult.get(i).length();
for (int x = 0; x < sL; x++) {
if (Character.isLetter(stringResult.get(i).charAt(x))) {
yearCount = 0;
System.out.println("index: " + i);
columnName = stringResult.get(i);
columnName = columnName.replace(" ", "_");
System.out.println(columnName);
i++;
break;
}
}
yearCount++;
String value = stringResult.get(i);
System.out.println("Year: " + stringResult.get(yearCount) + " Value: " + value + " Stock: " + ticker + " Column: " + columnName );
if (!(columnName == null)) {
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUE ('" + ticker + "','" + stringResult.get(yearCount) + "','" + value + "')";
String writeValues2 = "UPDATE BalanceSheet "
+ "SET ticker = '" + ticker + "', "
+ "Year = '" + stringResult.get(yearCount) + "', "
+ columnName + " = '" + value + "' "
+ "WHERE ticker = '" + ticker + "'";
statement.executeUpdate(writeValues2);
}
}
Towards the bottom of the code are two queries I tried, I'm trying to get all data organized by ticker and year into a table, "writeColumns" works but it's making a new row for every new "value" put into "columnName". My second attempt "writeColumns2" doesn't do anything.
I want to update the same row with a certain year for all values and then move onto the next year, then next ticker.
If I have understood your question correctly, you want to insert a row if it doesn't exists but update the values if it already does. You need to use ON DUPLICATE KEY UPDATE
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUES (?,?,?) "
+"ON DUPLICATE KEY UPDATE " + columnName +"=?";
Statement statement = conn.prepareStatement(writeValues);
statement.setString(1,ticker);
statement.setString(2,stringResult.get(yearCount));
statement.setString(3, value);
This will solve your immidiate problem provided you create a UNIQUE index on ticker,year
However there are lot's of other issues here.
An update for each column - Currently you are doing an insert/update for each column on the table. What you are supposed to do is to insert update all the columns at one.
You are not using prepared statements addressed in my code sample
You shouldn't be doing this at all the best way to batch process data is to use MYSQL's built in LOAD DATA INFILE command. If your data is not in a format that can be easily imported into mysql, what your Java code can do is to transform it into a format that can be. Such a code will be a lot simpler and neater than what you have now

Jena sparql (Dbpedia) query OPTIONAL filter gives no results but (http://dbpedia.org/snorql/) same query works

hello ive this query in this site working http://dbpedia.org/snorql/
PREFIX ontology: <http://dbpedia.org/ontology/>
SELECT DISTINCT ?author ?name ?wiki ?desc ?thumb WHERE {
?author a ontology:Book;
rdfs:label ?name;
ontology:wikiPageID ?wiki;
ontology:abstract ?desc.
OPTIONAL {?author <http://dbpedia.org/ontology/thumbnail> ?thumb }.
FILTER (lang(?name) = 'en')
FILTER (regex(?name, "lo") || regex(?desc, "lo"))
FILTER (lang(?desc) = 'en').
}ORDER BY ?name LIMIT 100
but in my jena queryFactory java class it only works if i remove Optional filter for thumbnail at this line :
OPTIONAL {?author <http://dbpedia.org/ontology/thumbnail> ?thumb }.
here is my jena java method that works :
private String authorQuery(String entity, String keyWord, String language) {
return addPrefix("rdfs: <http://www.w3.org/2000/01/rdf-schema#>") +
addPrefix("rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>") +
addPrefix("dbpprop: <http://dbpedia.org/property/>") +
addPrefix("ontology: <http://dbpedia.org/ontology/>") +
addQuery("SELECT DISTINCT ?author ?name ?wiki ?desc ?thumb WHERE {\n" +
"?author a ontology:" + entity + ";\n" +
"rdfs:label ?name;\n" +
"ontology:wikiPageID ?wiki;\n" +
"ontology:abstract ?desc;\n" +
"<http://dbpedia.org/ontology/thumbnail> ?thumb.\n" +
"FILTER (lang(?name) = '" + language + "') " +
"FILTER (regex(?name, \"" + keyWord + "\") || regex(?desc, \"" + keyWord + "\"))\n" +
" FILTER (lang(?desc) = '" + language + "')." +
"}\n" +
"ORDER BY ?name\n" +
"LIMIT 40000");
}
but as soon as i add optionnal keyword in this line :
"<http://dbpedia.org/ontology/thumbnail> ?thumb.\n" +
No result are returned, can someone tell me why? :(
PS : it work well without OPTIONAL FILTER
Edit : whole DbpediaQuery class
public class DbPediaQuery {
//array of authors
private DbPediaQuery() {
}
public static DbPediaQuery createDbPediaQuery() {
return new DbPediaQuery();
}
public LinkedList<Entity> queryAuthor(String entity, String keyWord, String language) {
LinkedList<Entity> temp = new LinkedList<>();
Query query = QueryFactory.create(authorQuery(entity, keyWord, language));
QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);
try {
temp.addAll(collectAuthors(qexec.execSelect()));
} catch (Exception e) {
e.printStackTrace();
}
return temp;
}
private String authorQuery(String entity, String keyWord, String language) {
return addPrefix("rdfs: <http://www.w3.org/2000/01/rdf-schema#>") +
addPrefix("rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>") +
addPrefix("dbpprop: <http://dbpedia.org/property/>") +
addPrefix("ontology: <http://dbpedia.org/ontology/>") +
addQuery("SELECT DISTINCT ?author ?name ?wiki ?desc ?thumb WHERE {\n" +
"?author a ontology:" + entity + ";\n" +
"rdfs:label ?name;\n" +
"ontology:wikiPageID ?wiki;\n" +
"ontology:abstract ?desc;\n" +
"<http://dbpedia.org/ontology/thumbnail> ?thumb.\n" +
"FILTER (lang(?name) = '" + language + "') " +
"FILTER (regex(?name, \"" + keyWord + "\") || regex(?desc, \"" + keyWord + "\"))\n" +
" FILTER (lang(?desc) = '" + language + "')." +
"}\n" +
"ORDER BY ?name\n" +
"LIMIT 40000");
}
private LinkedList<Entity> collectAuthors(ResultSet results) {
LinkedList<Entity> temp = new LinkedList<>();
while (results.hasNext()) {
Entity a = new Entity();
QuerySolution row = results.next();
String fullName = row.get("name").toString().substring(0, row.get("name").toString().indexOf("#"));
String biography = row.get("desc").toString().substring(0, row.get("desc").toString().indexOf("#"));
a.setTitle(fullName);
a.setWikiID(Integer.parseInt(row.get("wiki").toString().substring(0, row.get("wiki").toString().indexOf("^"))));
if (!row.get("thumb").toString().isEmpty())
a.setPictureURL(row.get("thumb").toString());
else
a.setPictureURL("http://www.google.fr/imgres?imgurl=http%3A%2F%2Fwww.elated.com%2Fres%2FImage%2Farticles%2Fmanagement%2Fapache%2Fmaking-a-custom-error-page%2Fapache_404_default.gif&imgrefurl=https%3A%2F%2Fgithub.com%2Fjdorn%2Fphp-reports%2Fissues%2F43&h=241&w=400&tbnid=KQI5AbkkVp3-uM%3A&zoom=1&docid=6Bd7CTaQ291_UM&ei=5AU0VceoI87WPYOvgCg&tbm=isch&iact=rc&uact=3&dur=3255&page=1&start=0&ndsp=20&ved=0CDYQrQMwBw");
a.setBiography(biography);
temp.add(a);
System.out.println("FAAT" + a.getTitle());
}
return temp;
}
private String addPrefix(String prefix) { return "PREFIX " + prefix + "\n"; }
private String addQuery(String query) { return query; }
}
ok i figured it out after logging several things... First ive loged the resultset size, with the optional filter it gave me more results than if i put no optional filter... 2383 vs 2103(without optional).. then i noticied that if
a.setPictureURL(row.get("thumb2").toString()); is empty or null the loop dont continue... it stoped after 14 results and gave me no return for this method :
private LinkedList<Entity> collectAuthors(ResultSet results) {
LinkedList<Entity> temp = new LinkedList<>();
while (results.hasNext()) {
Entity a = new Entity();
QuerySolution row = results.next();
String fullName = row.get("name").toString().substring(0, row.get("name").toString().indexOf("#"));
String biography = row.get("desc").toString().substring(0, row.get("desc").toString().indexOf("#"));
a.setTitle(fullName);
a.setWikiID(Integer.parseInt(row.get("wiki").toString().substring(0, row.get("wiki").toString().indexOf("^"))));
if (!row.get("thumb").toString().isEmpty())
a.setPictureURL(row.get("thumb").toString());
a.setBiography(biography);
temp.add(a);
System.out.println("FAAT" + a.getTitle());
}
return temp;
}
so i just checked with if(row.getResource("thumb2")!=null) like that
if(row.getResource("thumb")!=null)
a.setPictureURL(row.get("thumb").toString());
and then the loop continued ---> problem solved
Thanks everyone for your hints and be carefull of empty reslutset columns with Jena

JDBC - Query returns no values

I am trying to make a query that returns a simple series of results using JDBC on a java class. The Query only needs 1 join for it to work yet, for some reason, it does not return any values. However, when this query is ran on the Oracle SQL Developer, the correct results are shown. below is the code i am currently using.
To Access Database
query = "select h.house_id, h.house_address, h.house_type, h.status, l.firstname, l.surname, h.price_per_month "
+ "from houses_tbl h join landlord_tbl l on l.landlord_id = h.landlord_id";
conn = connectToDatabase();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
System.out.println(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
To Retrieve Data
response.setContentType("application/json");
fullJsonString = "{";
fullJsonString += "\"houses\":[";
ArrayList<HouseObj> allHouses = new ArrayList<HouseObj>();
try {
while (rs.next()) {
int houseID = rs.getInt(1);
Struct address = (Struct) rs.getObject(2);
Object[] taskAddress = address.getAttributes();
String houseAddressStreet = taskAddress[0].toString();
String houseAddressTown = taskAddress[1].toString();
String houseAddressCounty = taskAddress[2].toString();
String houseAddressCountry = taskAddress[3].toString();
String houseAddressPostcode = taskAddress[4].toString();
String houseFullAddress = houseAddressStreet + ", "
+ houseAddressTown + ", " + houseAddressCounty
+ ", " + houseAddressCountry + ", "
+ houseAddressPostcode;
String type = rs.getString(3);
String status = rs.getString(4);
String landlord = rs.getString(5)+" "+rs.getString(6);
int price = rs.getInt(7);
HouseObj newClient = new HouseObj(houseID,
houseFullAddress, type, status, landlord, price);
allHouses.add(newClient);
}
System.out.println("Number Of Houses : "+allHouses.size());
for (int i = 0; i < allHouses.size(); i++) {
if (i == allHouses.size() - 1) {
fullJsonString += "{\"id\":\""
+ allHouses.get(i).getHouseId() + "\","
+ "\"address\":\""
+ allHouses.get(i).getAddress() + "\","
+ "\"type\":\""
+ allHouses.get(i).getType() + "\","
+ "\"status\":\""
+ allHouses.get(i).getStatus() + "\","
+ "\"landlord\":\""
+ allHouses.get(i).getLandlord() + "\","
+ "\"price\":\""
+ allHouses.get(i).getPrice() + "\"}";
} else {
fullJsonString += "{\"id\":\""
+ allHouses.get(i).getHouseId() + "\","
+ "\"address\":\""
+ allHouses.get(i).getAddress() + "\","
+ "\"type\":\""
+ allHouses.get(i).getType() + "\","
+ "\"status\":\""
+ allHouses.get(i).getStatus() + "\","
+ "\"landlord\":\""
+ allHouses.get(i).getLandlord() + "\","
+ "\"price\":\""
+ allHouses.get(i).getPrice() + "\"},";
}
}
fullJsonString += "]}";
} //Catch Exception Below
Output
Number Of Houses : 0
{"houses":[]}
Any help to resolve this is greatly appreciated.
From your posted code, I don't see any printing of the resultset.
How do you know it's not returning anything?
Can you put a print statement before/after the while (rs.next) cycle (an if, a counter) to see if it' s actually empty?
If it is empty, try removing table alias from your query
EDIT:
Modify the query in "select house_id from houses_tbl", execute the query and exactly after
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
put
if (rs.next()){
System.out.println("Got house!");
}else{
System.out.println("No houses here!");
}
and momentarily comment out/bypass the printing code. This is to check baseline operativity of you env in that context. If this doesn't work, must be a database/driver issue, to me

Categories