java.sql.SQLSyntaxErrorException: ORA-00903: invalid table name - java

I have all table names in a drop down list in a java application.
I want display the number of records in a table on JLabel.
but I'm getting the following error
java.sql.SQLSyntaxErrorException: ORA-00903: invalid table name
I have tried this:
try {
String tableName = LoginFrame.userName + "." + this.ddlTableName.getSelectedItem().toString();
JOptionPane.showMessageDialog(null, tableName);
pst = (OraclePreparedStatement) con.prepareStatement("select count(*) as num from '" + tableName + "'");
rs = pst.executeQuery();
while (rs.next()) {
this.lblRecordStat.setText(rs.getString("num"));
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
System.out.println(ex);
}

In Oracle, quotes ('s) are used to denote string literals. Object names (such as tables) should not be surrounded by them. Lose the quotes and you should be OK:
pst = (OraclePreparedStatement) con.prepareStatement
("select count(*) as num from " + tableName);

You are passing string as table name. Table names in Oracle can be either inside `` qoutes or without any quotes.
pst = (OraclePreparedStatement) con.prepareStatement("select count(*) as num from " + tableName );
or
pst = (OraclePreparedStatement) con.prepareStatement("select count(*) as num from `" + tableName + "`");

Related

java sql insert timestamp java.sql.SQLSyntaxErrorException

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+"')";

Java SQLite Select Query

I am trying to complete my Java Code to execute a SELECT Query that will write the Results into Sysout.
Here is my Code:
public void PullFromDB() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
String sql = "SELECT * FROM " + Name + ";";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
Integer ID = rs.getInt("id");
System.out.println("ID = " + ID.toString());
String entry = rs.getString(Properties.get(j));
System.out.println(Properties.get(j) + "=" + entry);
j++;
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I sysout my SQL Query it looks like this:
CREATE TABLE IF NOT EXISTS Cars(ID INTEGER PRIMARY KEY AUTOINCREMENT,AnzSitze TEXT,Marke TEXT,Pferdestärke TEXT);
INSERT INTO Cars(AnzSitze,Marke,Pferdestärke) VALUES('vier','Audi','420');
SELECT * FROM Cars;
Those are just some examples I put in.
maybe create and propabley insert has failed, i see none-ascii characters in filed name Pferdestärke try to use valid names
check this
Permitted characters in unquoted identifiers:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,
underscore)
Extended: U+0080 .. U+FFFF
so replace the filed name Pferdestärke to Pferdestarke in all qrys and try again

Java JDBC SQLite update entry not working

I have created a database and a set of table using JDBC and SQLite in Eclipse.
I am trying to update the table using the following code:
public static void update()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery( "SELECT * FROM CUSTOMERS;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully");
}
As far as I can understand the SQL syntax I m using says:
update the table customers2 and set the address as Byron where phone =2
But am getting the following error:
java.sql.SQLException: no such column: Byron
Which tells me it is interpreting my request as asking to alter the column named Byron, which is not what I believe the code to be saying?
As per SQL syntax, varchar values should be used with single quotes so update this:
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
to
String sql = "UPDATE CUSTOMERS2 set ADDRESS = 'Byron' WHERE PHONE=2;";
If you don't use the single quotes, SQL assumes that you are trying to set the value using a different column and hence it throws the error:
java.sql.SQLException: no such column: Byron
ADVICE: Use PreparedStatment for dynamic parameter queries
PreparedStatement stmt;
String sql = "UPDATE CUSTOMERS2 set ADDRESS=? WHERE PHONE=?";
stmt = c.prepareStatement(sql);
stmt.setString(1, "Byron");
stmt.setInt(2, 2);
stmt.executeUpdate();

select same value from N rows in a mysql database

I m new to mysql and m trying to select N rows from a mysql table in eclipse. Now, i want to select N rows of same value from the database. I am using the following code
User user= null;
ArrayList<User> searchedUsers = new ArrayList<User>();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
String authenticationSql;
authenticationSql = "SELECT * FROM users WHERE " + searchIn + " = ?";
log.info(authenticationSql);
stmt = (PreparedStatement) dbConn.prepareStatement(authenticationSql);
stmt.setString(1, searchFor);
rs = stmt.executeQuery();
while (rs.next()) {
user = new User(rs.getString("username"),
rs.getInt("user_type"), OnlineStatus.ONLINE);
searchedUsers.add(user);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
log.error("SQLException: " + ex.getMessage());
log.error("SQLState: " + ex.getSQLState());
log.error("VendorError: " + ex.getErrorCode());
}
The problem is this code only returns me the first value of the search and not the rest of the values are selected from the database. Can please some one point out what i m doing wrong here. Any help will be appreciated. Thanks.
You cannot use count(*) in statement like this.
It should give you some error like Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause
I think it's the COUNT(*) from your SELECT that is grouping your results. Try without it

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