Would you be that kind and tell me whats wrong in here? conn is DriverManager.getConnection(DB_URL)
try {
PreparedStatement prepStmt = conn.prepareStatement(
"UPDATE week SET ?=? WHERE id>=? AND id<=?");
prepStmt.setString(1, s);
prepStmt.setFloat(2, x);
prepStmt.setInt(3, c);
prepStmt.setInt(4, d);
prepStmt.executeUpdate();
} catch(SQLException e) {
System.err.println("Error during data update");
e.printStackTrace();
}
Error is in first line of "try" and it goes like "SQL error or missing database (near "?": syntax error)". I have to add that when I put this statement in cmd with "?" substituted with values it works as charm.
You can't pass column names as parameters to the prepared statement. You can only pass values as parameters :
try {
PreparedStatement prepStmt = conn.prepareStatement(
"UPDATE week SET some_column_name=? WHERE id>=? AND id<=?");
prepStmt.setFloat(1, x);
prepStmt.setInt(2, c);
prepStmt.setInt(3, d);
prepStmt.executeUpdate();
} catch(SQLException e) {
System.err.println("Error during data update");
e.printStackTrace();
}
You cannot pass a column name to the PreparedStatement. What you could do to overcome this is change it in the string.
try {
PreparedStatement prepStmt = conn.prepareStatement(
"UPDATE week SET " + s + " =? WHERE id>=? AND id<=?");
prepStmt.setFloat(1, x);
prepStmt.setInt(2, c);
prepStmt.setInt(3, d);
prepStmt.executeUpdate();
} catch(SQLException e) {
System.err.println("Error during data update");
e.printStackTrace();
}
You should not do ? = ? you should specify the field id = ?...or whatever field you want there.
PreparedStatement prepStmt = conn.prepareStatement(
"UPDATE week SET columnName=? WHERE id>=? AND id<=?");
As it was mentioned you can not pass column names or sql syntax to the PreparedStatement. however you can use String.format() to pass anything to your sql:
try {
String sql = "UPDATE week SET %s=? WHERE id>=? AND id<=?";
sql = String.format(sql , "s")
PreparedStatement prepStmt = conn.prepareStatement(sql);
prepStmt.setFloat(1, x);
prepStmt.setInt(2, c);
prepStmt.setInt(3, d);
prepStmt.executeUpdate();
} catch(SQLException e) {
System.err.println("Error during data update");
e.printStackTrace();
}
sa you can see ? = ? is replaced with %s = ? and later the column name was replaced with String.format and later the String was passed to the PreparedStatement.
however this should not be used pass data because it defies the purpose of PreparedStatements.
Related
I get an sql error when trying to insert something into my DB.
I give a bunch of input to my method, convert that input into strings or sql time and want to store it.
public static void setCourseList(String courseDescription, String courseName, LocalTime courseStart, LocalTime courseEnd, LocalDate courseDate, DayOfWeek courseDay) {
Connection conn = null;
try {
// db parameters
// path to db relative to run time directory
String url = "jdbc:sqlite:Holiday.db";
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
conn = DriverManager.getConnection(url);
System.out.println("Connected");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement(sqlInsertCourse);
pstmt.setString(1, courseName);
String courseStartString = courseStart.toString();
pstmt.setString(2, courseStartString);
java.sql.Time courseEndTime = Time.valueOf(courseEnd);
pstmt.setTime(3, courseEndTime);
java.sql.Date courseDateDate = java.sql.Date.valueOf(courseDate);
pstmt.setDate(4, courseDateDate);
String courseDayString = courseDay.toString();
pstmt.setString(5, courseDayString);
pstmt.executeUpdate();
pstmt.close();
System.out.println("Connection to SQLite has been established.");
// create tables if they do not exists
stmt.execute(sqlInsertCourse);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
I would expect it to store the input in my db.
I do get an [SQLITE_ERROR] SQL error or missing database (near ")": syntax error) error instead.
Any help is appreciated.
I am new to sql.
Change
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
To
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?);"; //<<<<<<<<<< extra comma removed
As per the comment on the line the final comma after the last ? has been removed.
Same as what Mike has answered, you can change it to
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (""put values here"");";
If you are wondering why it doesn't throw you an error, it's because there is no syntax error in the java, there's an error in the SQL which only the database can throw, but you're computer can't recognize. Hope this answers your question.
I tried to save / edit / delete a new row in the database. writing in the gui values to be saved with getText ()
here is the code
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql;
sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (txt_isbn, txt_disp, txt_titolo, txt_casa, txt_autore, txt_genere, txt_prezzo)";
stmt = conn.createStatement();
emps = stmt.executeQuery(sql);
String ISBN= txt_isbn.getText();
String DISPONIBILITA= txt_disp.getText();
String TITOLO= txt_titolo.getText();
String CASA_EDITRICE= txt_casa.getText();
String CODICE_AUTORE= txt_autore.getText();
String GENERE= txt_genere.getText();
String PREZZO = txt_prezzo.getText();
JOptionPane.showMessageDialog(null, "SALVATO");
}catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null, e);
}
finally
{
try{
if (emps != null)
emps.close();
}
catch (SQLException e) { }
try
{
if (stmt != null)
stmt.close();
}
catch (SQLException e) { }
}
Getting this error: column not allowed here
Above code just takes care of insert operation. How can I delete and modify table record?
You have asked 2 different questions here
1. Column not allowed here
This happened because you have not passed values for any of parameter into insert statement.
I am not sure about your requirement however I will use PreparedStatement for this scenario.
Example
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "MindPeace");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement .executeUpdate();
2. This code is only to save the data, delete, and modify an entire row how can I do?
Answer is very simple. You have to write code for the same :)
You need 3 SQL statement which has DELETE and UPDATE operation just like insert in above example.
String sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, "
+ "CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.createStatement()) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);
String ISBN = txt_isbn.getText();
String DISPONIBILITA = txt_disp.getText();
String TITOLO = txt_titolo.getText();
String CASA_EDITRICE = txt_casa.getText();
String CODICE_AUTORE = txt_autore.getText();
String GENERE = txt_genere.getText();
BigDecimal PREZZO = new BigDecimal(
numberFormat.parse(txt_prezzo.getText()).doubleValue())
.setScale(2);
stmt.setString(1, ISBN);
stmt.setString(2, DISPONIBILITA);
stmt.setString(3, TITOLO);
stmt.setString(4, CASA_EDITRICE);
stmt.setString(5, CODICE_AUTORE);
stmt.setString(6, GENERE);
stmt.setBigDecimal(7, PREZZO);
int updateCount = stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "SALVATO");
} catch(SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
Try-with-resources closes the stmt automatically.
The prepared statement replaces the value in the SQL with something like:
INSERT INTO table(column1, colum2, ....)
VALUES('De\'l Rey',
1234.50,
...)
for:
"De'l Rey"
1.234,50
updateCount should be 1 on success.
Wooow..true!!
I created three buttons to delete / update / insert and now it all works and automatically updates the tables.
you've been very very great. Thank you very much.
one last thing.
if I wanted to insert an error message when I delete / update etc "book not found" I tried to create an if:
Boolean found = false;
try{
sql= delete......
etc
if (!found)
JOptionPane.showMessageDialog(null, "NOT FOUND","ERRORE",JOptionPane.WARNING_MESSAGE);
etc...
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql= "DELETE FROM progetto.libro WHERE isbn =?"; /
pst=(OraclePreparedStatement) conn.prepareStatement(sql);
pst.setString (1, txt_isbn.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "ELIMINATO");
Update_table();
txt_isbn.setText("");
txt_disp.setText("");
txt_titolo.setText("");
txt_casa.setText("");
txt_autore.setText("");
txt_genere.setText("");
txt_prezzo.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
if you find the book must exit the book removed, or "not found". but as I deployed I always come out "deleted". why?
thanks again
When writing to a mySQL db, i get the following error:
java.sql.BatchUpdateException: Unknown column 'ALFA' in 'where clause'
this is my java code:
public void pushWinner(String game, String teamW) throws SQLException{
String[] t1 = game.split("-");
String statement = "update games set winner=(?) where team1 = "+t1[0]+" AND team2 = "+t1[1];
try (PreparedStatement pstmt = conn.prepareStatement(statement)) {
pstmt.setString(1, teamW);
pstmt.addBatch();
pstmt.executeBatch();
pstmt.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
I realy can't see what's wrong with the where clause...
EDIT
See my comment, forgot to mention what 'ALFA' is.
Data types for team1 and team2 are both VARCHAR(45).
try this: since datatype of column team1 and team2 are VARCHAR so put single quote to compare it.
queryString= "update games set winner=(?) where team1 = '"+t1[0]+"' AND team2 = '"+t1[1]+"'";
If your datatype is string that you need Single Quote around your passed variable values
something like this...
String statement = "update games set winner=(?) where team1 = '"+t1[0]+"' AND team2 = ' "+ t1[1] + "'";
Your asking for trouble making sql like this. use a prepared statement with seperate parameters instead of inline param building. will stop issues like this and take care of parameter escaping. So use ? in the main sql to denoate location of a parm and use .setString(1, value); to set first (yes its 1 based). Or setInt(1, intValue) ... depending on data type. For date use java.sql.Timestamp - can convert a calendar to date and java.util.Date to sql timestamp OR new javax.time or joda. But dont use inline.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Why
ease of programming and
https://www.owasp.org/index.php/SQL_Injection
Copied from the java tutorial :
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement =
"update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? " +
"where COF_NAME = ?";
try {
con.setAutoCommit(false);
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
} finally {
if (updateSales != null) {
updateSales.close();
}
if (updateTotal != null) {
updateTotal.close();
}
con.setAutoCommit(true);
}
}
I am trying to update a table using Java JDBC. The method I am using does not throw any errors but the table is not updating. The create table method is below:
public static void Table()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS CUSTOMERS2 " +
"(PHONE TEXT PRIMARY KEY NOT NULL," +
" SURNAME TEXT NOT NULL, " +
" FIRSTNAME TEXT NOT NULL, " +
" HOME TEXT, " +
" ADDRESS TEXT, " +
" POSTCODE Text)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Customers2 created successfully");
}
The update method is below:
public static void updateCustomers()
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
pstmt = c.prepareStatement(query); // create a statement
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
pstmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully HELLO");
}
I have tried to find some clear instructions on this but cant find any. I do not really understand JDBC and prepared statement very well
When autoCommit is false (c.setAutoCommit(false);), you must manually commit the transaction...
Add...
c.commit()
After pstmt.executeUpdate();
You code also has a flaw, in that if some kind of error occurs during the preparation or execution of the statement, both the Connection and PreparedStatement could be left open, causing a resource leak
If you're using Java 7+ you can use the try-with-resources feature, for example...
try {
Class.forName("org.sqlite.JDBC");
try (Connection c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db")) {
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
try (PreparedStatement pstmt = c.prepareStatement(query)) {
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
c.commit();
}
} catch (SQLException exp) {
exp.printStackTrace();
}
} catch (ClassNotFoundException exp) {
exp.printStackTrace();
System.out.println("Failed to load driver");
}
This will ensure that regardless of how you leave the try block the resource will be closed.
You might also consider taking a look at the JDBC(TM) Database Access
Your update method will set ADDRESS to 1 if there is any row in table with PHONE = does this work.
Try to put Address in 1st Input parameter and Phone 2nd Input parameter
When a connection is created, it is in auto-commit mode.
We need to use [setAutoCommit] method only when we need to make Auto Commit false and make it manual commit after executing the query.
More details at Oracle site on JDBC Transaction.
while (tokens.hasMoreTokens())
{
keyword = tokens.nextToken();
System.out.println("File= "+fileid+" Keyword=" + keyword);
stmt.executeUpdate(
"INSERT into TEXTVALUEINVERTEDINDEX " + "(FILEID, KEYWORD) values ('"
+ fileid + "', '" + keyword + "')"
);
}
This is the loop in which I'm updating the rows. The problem I'm facing is that when i run this only 1 value gets updated and when I comment the stmt.executeUpdate() line it displays all the possible entries in the database.
You need to use preparedStatements...
PreparedStatement pStmt = connection.prepareStatement("INSERT into TEXTVALUEINVERTEDINDEX (FILEID, KEYWORD) values(?,?)");
while (tokens.hasMoreTokens())
{
keyword = tokens.nextToken();
System.out.println("File= "+fileid+" Keyword="+keyword);
pStmt.setString(1, fileid); //This might be pStmt.SetInt(0, fileid) depending on teh type of fileid)
pStmt.setString(2, keyword);
pStmt.executeUpdate();
}
then using this you can extend to us batch update...
PreparedStatement pStmt = connection.prepareStatement("INSERT into TEXTVALUEINVERTEDINDEX (FILEID, KEYWORD) values(?,?)");
while (tokens.hasMoreTokens())
{
keyword = tokens.nextToken();
System.out.println("File= "+fileid+" Keyword="+keyword);
pStmt.setString(1, fileid); //This might be pStmt.SetInt(0, fileid) depending on teh type of fileid)
pStmt.setString(2, keyword);
pStmt.addBatch();
}
pStmt.executeBatch();
Not sure why your code isn't working though - but this will probably help in the long run...
Your code should work. Make sure the sentence is not throwing any Exceptions when running by surrounding it with a try/catch block:
try {
stmt.executeUpdate("INSERT into TEXTVALUEINVERTEDINDEX " +
"(FILEID, KEYWORD) "+"values ('"+fileid+"', '"+keyword+"')");
} catch (SQLException e) {
e.printStackTrace();
}
You should also consider using a PreparedStament instead since its use is very appropriate for your described scenario:
Something like this:
String sql = "insert into textvalueinvertedindex (fileid, keyword) values (?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
while (tokes.hasMoreTokens()) {
keywords = tokens.nextToken();
pstmt.setString(1, fileid);
pstmt.setString(2, keyword);
pstmt.executeUpdate();
}
pstmt.close();
If you want all updates to be applied at once you can use batch execution, here is an example
Your date range and filter selection contained no results.