java sql insert timestamp java.sql.SQLSyntaxErrorException - java

i am trying to insert timestamp to my database but i keep getting java.sql.SQLSyntaxErrorException:
here is my code
java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
System.out.println(sqlDate);
Here the insertion and connection to DB
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1598/VotingDB", "app", "app");
Statement st = conn.createStatement();
String sql = "INSERT INTO VOTES (CANDIDATE_NAME,VOTER_SSN,TIMESTAMP) "
+ "VALUES ('" + Candidate_Name + "','" + ssn + "'," + TimeStamp + ")";
st.executeUpdate(sql);
st.close();
conn.close();
} catch (SQLException ex) {
System.out.println("Connection failed adding vote " + ex);
}
Error
2017-04-09 20:10:02.825 Connection failed adding vote
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "20" at
line 1, column 94.

You should to put your time between '' like this :
"VALUES ('" + Candidate_Name + "','" + ssn + "', ' " + TimeStamp + "')";
But this is not secure enough, you have to use PreparedStatement instead to avoid any SQL Injection.
For example :
String sql = "INSERT INTO VOTES (CANDIDATE_NAME, VOTER_SSN, TIMESTAMP) VALUES (?, ?, ?)";
try (PreparedStatement stm = connection.prepareStatement(sql)) {
stm.setString(1, Candidate_Name );
stm.setString(2, ssn );
stm.setDate(3, TimeStamp);
stm.executeUpdate();
}

Shouldn't you enclose TimeStamp variable in simple quotes?
String sql = "INSERT INTO VOTES (CANDIDATE_NAME,VOTER_SSN,TIMESTAMP) "
+ "VALUES ('"+Candidate_Name +"','"+ssn +"','"+TimeStamp+"')";

Related

SQL query sees the value as a column name

I am trying to make a connection to a database and then run an INSERT INTO query, but when the code runs, i get the error: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'BLUE'.
As you can see in my code below, i give "BLUE" as an value instead of an column name. Does anyone knows what i am doing wrong? p.s. color is an Enum, all the other values are doubles.
String query = "INSERT INTO [oval] " +
"(anchorX, anchorY, width, height, weight, color) VALUES " +
"(" + drawingItem.getAnchor().getX() +
", " + drawingItem.getAnchor().getY() +
", " + drawingItem.getWidth() +
", " + drawingItem.getHeight() +
", " + ((Oval) drawingItem).getWeight() +
", " + drawingItem.getColor().toString() + ")";
initConnection();
Statement myStmt = con.createStatement();
rowsAffected = myStmt.executeUpdate(query);
closeConnection();
EDIT ANSWER:
String query = "INSERT INTO [oval] VALUES (?,?,?,?,?,?)";
initConnection();
PreparedStatement myPrepStmt = con.prepareStatement(query);
myPrepStmt.setDouble(1, drawingItem.getAnchor().getX());
myPrepStmt.setDouble(2, drawingItem.getAnchor().getY());
myPrepStmt.setDouble(3, drawingItem.getWidth());
myPrepStmt.setDouble(4, drawingItem.getHeight());
myPrepStmt.setDouble(5, ((Oval)drawingItem).getWeight());
myPrepStmt.setString(6, drawingItem.getColor().toString());
rowsAffected = myPrepStmt.executeUpdate();
closeConnection();
As suggested, use parametrized query to prevent SQL injection. As for the problem in hand, you must use single quote to each string values.
Ex:
"('" + drawingItem.getAnchor().getX() +
"', '" +
Correct way would be:
String query = "INSERT INTO [oval] " +
"(anchorX, anchorY, width, height, weight, color) VALUES " +
"(?, ?, ?, ?, ?, ?)";
initConnection();
int i = 1;
Statement myStmt = con.prepareStatement(query);
myStmt.setInt(i++, drawingItem.getAnchor().getX());
myStmt.setInt(i++, drawingItem.getAnchor().getY());
myStmt.setString(i++, drawingItem.getWidth());
myStmt.setString(i++, drawingItem.getHeight());
myStmt.setFloat(i++, ((Oval) drawingItem).getWeight());
myStmt.setString(i++, drawingItem.getColor().toString());
rowsAffected = myStmt.executeUpdate();

Code exiting try and going in catch after first executeQuery?

I am a beginner in android development. This is a part of my sign up code in my first android studio app: The code is going into catch right after the first execute query line and not executing my second query. If i check the Database a user is added but not a fan.
Any idea why? Any help is appreciated.
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
Statement stmt = con.createStatement();
String query1 = "INSERT INTO Usertb Values ('" + userid + "', '" + Password + "', '" + 1 + "')";
stmt.executeQuery(query1);
String query = "INSERT INTO Fan Values ('" + FirstName + "', '" + LastName + "','" + Age + "', '" + Email + "', '"
+ null + "', '" + i + "', '" + null + "')";
rs = stmt.executeQuery(query);
if (rs.next()) {
z = "Sign Up successfull";
isSuccess = true;
}
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
}
One has to use executeUpdate (INSERT/UPDATE) instead of executeQuery.
String sql = "INSERT INTO Usertb(userid, passw, n) VALUES (?, PASSWORD(?), ?)";
try (PreparedStatement stmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, userName);
stmt.setString(2, password);
stmt.setInt(3, 1);
int updateCount = stmt.executeUpdate(query1); // 1 when 1 record inserted
if (updateCount != 0) {
// If you want to use an autincrement primary key:
try (ResultSet rsKeys = stm.getGeneratedKeys()) {
if (rsKeys.next()) {
long id = rsKeys.getLong(1);
}
}
}
} // Closes stmt
Furthermore it is very important to use prepared statements to prevent SQL injection. It also takes care of single quotes and backslash in the strings.
Additionally there is shown how to use AUTOINCR fields, to retrieve a database generated key, for example for the second INSERT.
For the second use a new PreparedStatement.
Passwords should better be stored encrypted in the database, should someone steal the data. You might look into that subject. My solution is quite minimal, look for seeding and other encryption functions.

Resultset.next returns true but doesn't return the value

I am trying to read from a mysql table and I am doing the following:
protected void pushRegisteredStudentsData() {
try {
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String userID = "SELECT * FROM STUDENT";
rs = stmt.executeQuery(userID);
while (rs.next()) {
int id = rs.getInt("ID");
this.studentID = id;
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
stmt.executeUpdate(insertSql);
}
} catch (SQLException e) {
}
}
..but for some reason,
while (rs.next()) {
int id = rs.getInt("ID");
always returns the same ID, even though the table has different ID's on every line!
Does anyone have an idea why that might be?
Thank you in advance! :(
EDIT:
I was using a single statement to execute 2 updates, which was causing the problem!
It is a bit weird that it returns always the same value because it should only return the first value ONCE.
If you print the stacktrace instead of just catching the exception and doing nothing, you will see that it will print something like:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
You are using THE SAME statement for a Select and then for an Insert. This causes the resultSet that is "attached" to the Statement to close because it is not supposed to be used again.
It can be easily fixed by creating another statement:
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(insertSql);

Unknown SQL Issue with INSERT sentence

Basically I'm trying to update a Database table with the values of a getSelectRow. As you can see, the query finds the correct data, but has huge issues when actually trying to add it to the database.
The error is in the SQL syntax, but I don't know where I'm going wrong. Please Help.
This is the query that it executes, but I have no idea why it isn't updating the table.
INSERT INTO customerdetails
FName = 'Tim'
AND SName = 'Cooley'
AND Address = '52 Buckminster Drive Dorridge Solihull West Mids'
AND Postcode = 'B93 8PG'
Java code:
private void sendBtnMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
int insertRow = newOrderTbl.getSelectedRow();
int col2 = 0;
String sql3 = "INSERT INTO customerdetails VALUES "
+ "FName = '" + newOrderTbl.getValueAt(insertRow, col2) +"'"
+ "AND SName = '" + newOrderTbl.getValueAt(insertRow, col2+1) +"'"
+ "AND Address = '" + newOrderTbl.getValueAt(insertRow, col2+2) +"'"
+ "AND Postcode = '" + newOrderTbl.getValueAt(insertRow, col2+3) +"'";
System.out.println(sql3);
try{
pst = conn.prepareStatement(sql3);
pst.executeUpdate(sql3);
JOptionPane.showMessageDialog(null, "Deleted");
CustomerTable();
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
To begin with, your SQL syntax is wrong (at least that it is a non-standard SQL syntax for your database engine). Second, your code is vulnerable to SQL Injection attack.
In order to solve both problems, you should use a PreparedStatement (that you're doing in the wrong way). A basic example from your code:
String sql = "INSERT INTO customerdetails (FName, SName, Address, Postcode) VALUES (?, ?, ?,?)";
PreparedStatement pst = conn.prepareStatemtnt(sql);
pst.setString(1, newOrderTbl.getValueAt(insertRow, col2));
pst.setString(2, newOrderTbl.getValueAt(insertRow, col2+1));
pst.setString(3, newOrderTbl.getValueAt(insertRow, col2+2));
pst.setString(4, newOrderTbl.getValueAt(insertRow, col2+3));
pst.executeUpdate();
//rest of code...
Assuming your SQL syntax will work, then you should pass the values as parameters, similar to the previous example:
String sql3 = "INSERT INTO customerdetails VALUES "
+ "FName = ?"
+ "AND SName = ?"
+ "AND Address = ?"
+ "AND Postcode = ?"
pst = conn.prepareStatement(sql3);
pst.setString(1, newOrderTbl.getValueAt(insertRow, col2));
pst.setString(2, newOrderTbl.getValueAt(insertRow, col2+1));
pst.setString(3, newOrderTbl.getValueAt(insertRow, col2+2));
pst.setString(4, newOrderTbl.getValueAt(insertRow, col2+3));
pst.executeUpdate();
//rest of code...
for update statement it will be -
String sql3 = "INSERT INTO customerdetails(FName,SName,Address,Postcode) VALUES "
+ " '" + newOrderTbl.getValueAt(insertRow, col2) +"',"
+ " '" + newOrderTbl.getValueAt(insertRow, col2+1) +"',"
+ " '" + newOrderTbl.getValueAt(insertRow, col2+2) +"',"
+ " '" + newOrderTbl.getValueAt(insertRow, col2+3) + "')";
Also you should use PreparedStatement for this.
Thanks
Please change it to
String sql3 = "INSERT INTO customerdetails(FName,SName,Address,Postcode) VALUES ("
+ "'" + newOrderTbl.getValueAt(insertRow, col2) +"'"
+ "'" + newOrderTbl.getValueAt(insertRow, col2+1) +"'"
+ "'" + newOrderTbl.getValueAt(insertRow, col2+2) +"'"
+ "'" + newOrderTbl.getValueAt(insertRow, col2+3) +"')";
The generated insert statement in your code seems invalid. Please see SQL Insert Statement for more information
Also, the better approach would be to create a dedicated Serverside DAO class to handle database operations.

java.sql.SQLSyntaxErrorException: Syntax error: Encountered "80" at line 1, column 1100

I get the following exception,
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "80" at line 1, column 1100.
when I try to insert like the following! Any idea what this could mean??!
String insertString = "insert into queries (data_id, query, "
+ "query_name, query_file_name, status) values(" + currentDataID + ", '"
+ params[1] + "', '" + params[2] + "', '"
+ params[3] + "', '" + params[4] + "')";
try {
Statement stmt = dbconn.createStatement();
stmt.execute(insertString, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if (rs != null && rs.next()){
currentDataID = (int) rs.getLong(1);
}
} catch (SQLException ex) {
}
Table definition,
CREATE TABLE queries (query_id INT not null primary key GENERATED "
+ "ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), data_id "
+ "INTEGER not null, foreign key (data_id) references data "
+ "(data_id), query LONG VARCHAR, query_name VARCHAR(150), "
+ "query_file_name VARCHAR(150),status VARCHAR(20))
Try this approach with a prepared statement:
String insert = "INSERT INTO queries (data_id, query, query_name," +
" query_file_name, status) VALUES (?,?,?,?,?)";
PreparedStatement stmt = dbconn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
// Why do you set this if you want the DB to generate it?
stmt.setInt(1, currentDataID); // or setLong() depending on data type
stmt.setString(2, params[1]); // I assume params is a String[]
stmt.setString(3, params[2]);
stmt.setString(4, params[3]);
stmt.setString(5, params[4]);
stmt.execute();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
// if it's an int, avoid the cast and use rs.getInt(1) instead
currentDataID = (int) rs.getLong(1);
}
I don't understand why you set the data_id while the later code expects the database to generate it... Your table definition would help.
This is probably happening because one of your params[] contains a quote character.
This problem is exactly why you shouldn't create SQL expressions like this, but should instead use a PreparedStatement. Please read up on SQL injection.

Categories