Im newbie in java and need help with getting rid of a comma in an sql query. anyone who can guide me in the right direction?
query = "UPDATE " + tablename + " SET ";
for(int i=0; i< columnnames.size(); i++)
{
query+= "'" + columnnames.get(i) + "' = '" + row[i] + "',";
}
query = StripLastComma(query); //Not sure how to do this in Java.
query +="' WHERE " + FirstColumn + " = '" + rowstandard + "'";
You can do this:
query = query.substring(0, query.length()-1);
at the place of "//Not sure how to do this in Java.".
But also:
1) As Makoto wrote use PreparedStatement. Also read a bit
about SQL injection and how to protect yourself from it.
2) Using StringBuilder instead of String would be better for your case.
That's because, it seems you use String and it is immutable.
So when deleting the last comma, you're actually creating a
whole new String object which is really not needed as other pointed
out in their comments.
Disregarding the already mentionned SQL injection problem, I would use a StringBuilder and do it like this to avoid that last comma.
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("UPDATE " + tablename + " SET ");
for(int i = 0; i < columnnames.size(); i++) {
if (i != 0) {
queryBuilder.append(",");
}
queryBuilder.append("'" + columnnames.get(i) + "' = '" + row[i] + "'");
}
queryBuilder.append("' WHERE " + FirstColumn + " = '" + rowstandard + "'");
query = queryBuilder.toString();
Firstly, you have a bug: you are quoting your column names when you should not.
The comma issue is easiest handled by making the logic different for the first iteration and putting the comma before the content, which neatly handles the edge case of there being only one column:
if (i > 0)
query += ",";
query += columnnames.get(i) + " = '" + row[i] + "'";
Your code is vulnerable to SQL injection, but if the only client is your own code (ie you know the new values of the columns are "safe") it's OK.
Related
I am trying to get data from a result set into my java application so that I can display it to the user. Something I'd like to implement is a partial search function that displays multiple rows of data based on an input string. If that string appears in any serial number in the database, it pulls that entire row and adds it to a string.
res is the ResultSet
public String searchToString() {
String temp = "";
try {
while(res.next()) {
temp = res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
} catch (SQLException se) {
System.out.println(se);
}
return temp;
}
I have tried changing the queries I use and figured out that the LIKE query was the best one. However, if I try outputting the string to a text area I only see one output where many more are supposed to be. I am definitely missing something from my code to tell it to continue adding the rest of the rows to the string, but I haven't come across anything on the Internet that can tell me what it is.
You are overwriting temp
//try +=
temp += res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
//or temp = temp +
temp = temp + res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
Here, resultSet.getInt() doesn't work, but I do not know what is wrong with my code.
I want to increment the value of the column (with the name as the variable 'attendance'). Using the SELECT statement I want to read the current value and by using UPDATE I want to increment the corresponding value by 1. But the problem is that int a = r.getInt("'" + attendance + "'"); doesn't work. It always returns the value 0 although the current value isn't 0 (e.g. 1). What is wrong with my code?
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:"+ x +".db");
s = c.createStatement();
r = s.executeQuery("SELECT '" + attendance + "' FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'");
while (r.next()){
int a = r.getInt("'" + attendance + "'");
int b = 1 + a;
String sql = "UPDATE viewer SET '" + attendance + "' = ? WHERE name = ? AND year = ? ";
p = c.prepareStatement(sql);
p.setInt (1,b);
p.setString (2,name);
p.setInt (3,year);
p.executeUpdate();
}
p.close();
c.close();
// r.getInt() value always 0
}
catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
Since you wrap the name of the column in single quotes, it is considered as the string literal 'attendance' and not the name of the column which is the value of the variable attendance.
Change to:
"SELECT " + attendance + " FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'"
(why do you concatenate the arguments name and year? Use placeholders ? just like the UPDATE statement)
and
"UPDATE viewer SET " + attendance + " = ? WHERE name = ? AND year = ? "
and
int a = r.getInt(attendance);
since you only have 1 column, you can use column index, instead of column names
int a = r.getInt(0);
for (String[] array : checkstore1) {
for (String element : array) {
String sql5 = "UPDATE product SET "
+ "pro_store = '" + element + "'" + ","
+ "WHERE pro_id = '" + array + "'";
stmt.executeUpdate(sql5);
}
}
Any suggestions on how to correct my code would be helpful, thanks!
"WHERE pro_id = '" + array + "'";
You should check if you really want to use a array here.You sql will be like
WHERE pro_id = '[Ljava.lang.String;#72ffb'
I think you should change array to a String value.
I'm wanting to insert an entry if it does not exist otherwise update the entry, I couldn't use the ON DUPLICATE KEY UPDATE, I got confused with the syntax. So I tried to do something like this:
final String QUERY = "REPLACE INTO skills SET VALUES (" + insert(player) + ") WHERE playername = '" + player.getUsername() + "'";
statement.execute(QUERY);
statement.close();
connection.close();
}
private static String insert(Player player) {
String stringToReturn = "'" + player.getUsername() + "',";
for (int index = 0; index < 25; index++) {
stringToReturn += player.getSkills().getLevels()[index] + "," + ((int) player.getSkills().getXp()[index]) + ",";
}
stringToReturn = stringToReturn.substring(0, stringToReturn.length() - 1);
return stringToReturn;
}
But that's incorrect syntax so I was wondering how I could do this?
playername is primary key
I think the correct syntax to make ON DUPLICATE KEY UPDATE work for you is:
"INSERT INTO skills (playerName, otherColumn)
VALUES ('" + player.getUsername() + "', '" + insert(player) +"')
ON DUPLICATE KEY UPDATE otherColumn = VALUES(otherColumn)";
Im having trouble reading from a CSV file
final String DELIMITER = ",";
Scanner fileScan = null;
Scanner dataSetScan = null;
String dataSet = null;
String sql = "";
File users = new File("user.txt");
String nickname = "";
String lastname = "";
String firstname = "";
String cartype = "";
String personimage = "";
String carimage = "";
int user_id = 0;
try {
fileScan = new Scanner(users);
} catch (Exception e) {
System.out.println(e);
}
while(fileScan.hasNext()){
dataSet = fileScan.nextLine();
dataSetScan = new Scanner(dataSet);
dataSetScan.useDelimiter(DELIMITER);
nickname = dataSetScan.next();
lastname = dataSetScan.next();
firstname = dataSetScan.next();
cartype = dataSetScan.next();
personimage = dataSetScan.next();
carimage = dataSetScan.next();
sql += "INSERT INTO users VALUES (";
sql += user_id++ + ", ";
sql += "'" + nickname + "', ";
sql += "'" + lastname + "', ";
sql += "'" + firstname + "', ";
sql += "'" + cartype + "', ";
sql += "'" + personimage + "', ";
sql += "'" + carimage + "' ";
sql += ");\n";
}
The above code wont work on the example file
alice,Wonder-Land,Alice,red Vauxhall Corsa,alice.jpg,alice_car.jpg
bob,Kett,Robert,,,
charlie,Carlos,Don,,,
However, it works just fine when there is a comma at the end of the line. (hvaing a comma here is not an option)
What can i do to make this work? It must be to do with my delimeter i think
Thank you
I wouldn't recommend using your own parser for CSV. CSV is surprisingly complex with little gotchas everywhere.
For instance, in CSV, it is legal to quote a column value with a comma in it
3 columns in this file
abc,"value1,value2",def
I recommend this library for java, it's very easy to use.
http://opencsv.sourceforge.net/
EDIT - May 2013
Since writing this post, I have switched to this library, which supports the CSV "standard" better and is actively developed.
http://supercsv.sourceforge.net/
Are you getting a NoSuchElementException from the following line?
carimage = dataSetScan.next();
If so you just need to wrap that with a hasNext check and perform a null check when you build your string.
if(dataSetScanner.hasNext()){
carimage = dataSetScan.next();
}
else{
carimage = null;
}
...
sql += carimage == null ? "NULL" : "'" + carimage + "' ";
I would recommend testing each token before inserting it,
But to answer your question, add an if condition before the last dataSetScan.next() call like so:
if (dataSetScan.hasNext()){
carimage = dataSetScan.next();
}