Oracle Java SQL Exception Error: ORA-0094 - java

I am trying to write a function for this button. I want to be able to pass it a textfield value and be able to go into my database to retrieve some information.....
Can somebody explain to me what is going on and provide me a solution to this madness?
Thank you all xD
I keep running into this stupid problem:
ACTION1 createdoracle.jdbc.driver.T4CConnection#484845aa
Exception:java.sql.SQLSyntaxErrorException: ORA-00904: "ART": invalid identifier
Code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//CLASS TYPE
//LIST ALL OFFERED CLASSES AND REVENUE
try{
String classtype = jTextField1.getText().trim();
if(classtype.equals("")){
JOptionPane.showMessageDialog(this, "Sorry Wrong input.... Please try again....");
}
else if(classtype != ""){
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection(
"jdbc:oracle:thin:#fourier.cs.iit.edu:1521:orcl",
"usr","pwd");
Statement stmt = conn.createStatement();
System.out.println("ACTION1 created"+conn+"\n\n");
String ct = jTextField1.getText().trim();
//String aa = "SELECT * FROM CLASS WHERE TYPE="+classtype;
//System.out.println(aa);
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE="+ct);
while (rset.next()) {
System.out.println(rset.getString("TITLE") + " ");
}
JOptionPane.showMessageDialog(this, "Class Type: "+classtype);
stmt.close();
conn.close();
System.out.println("Connection Closed");
}
catch(Exception sqle){
System.out.println("\nException:"+sqle);
}
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, "Please Retry input....", "Error", JOptionPane.ERROR_MESSAGE);
}
}

Let me guess ... does the ct String start with "ART" (or some variation)?
If so, the problem is that SQL requires quotes around string literals. Your query probably looks to Oracle something like this:
SELECT * FROM CLASS WHERE TYPE=Art of War
but it should look like
SELECT * FROM CLASS WHERE TYPE='Art of War'
There are two ways to fix this:
Assemble the query with quote characters around ct.
Write the query as "SELECT * FROM CLASS WHERE TYPE=?", use a PreparedStatement instead of a Statement and use the setString method to supply the parameter value.
If done properly, the second approach is both more secure and more efficient. (The problem with string-bashing the query and using Statement is that you are potentially making yourself vulnerable to SQL injection attacks.)

You're passing the value as part of the query, and the string concatenation you're doing makes the SQL into:
SELECT * FROM CLASS WHERE TYPE=ART
(where ART is the value of ct from the textfield) so it's trying to find a column on the table called ART. At an absolute minimum you need to quote the string:
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE='" + ct + "'");
But really don't do this; as #Andreas_D says you're leaving yourself open to SQL injection. Always use prepared statements and bind variables:
String sql = "SELECT * FROM CLASS WHERE TYPE=?";
PrepareStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ct);
ResultSet rset = stmt.executeQuery();

Related

Value of ResultSet when the SQL statement is a wrong syntax?

I am using mySQL. As you see, the SQL statement is wrong at SELECT. So, I wonder what value the rs is?
I hope to get some advice. I thank you so much;
String sql = "SELCT * FROM user WHERE username = '" + username + "' and password = '" + password + "'";
ResultSet rs = stm.executeQuery(sql);
There would be no value because Statement.executeQuery(String) would throw a SQLException. As the linked Javadoc says,
Returns:
a ResultSet object that contains the data produced by the given query; never null
Throws:
SQLException - if a database access error occurs, this method is called on a closed Statement, the given SQL statement produces anything other than a single ResultSet object, the method is called on a PreparedStatement or CallableStatement
It will return you an exception having message like syntax error.
Easiest way to find is to debug your code by putting break points in code & examining / watching values of variables . Most IDEs have these debugging features. In addition to Elliott Frisch's answer, if I restructure your code like below then in case of invalid / incorrect SQL, control comes to catch block and you can see that value of rs remains null.
public void executeQuery(Connection conn, String username,String password) {
String sql = "SELCT * FROM user WHERE username = '" + username + "' and password = '" + password + "'";
ResultSet rs = null;
Statement stm = null;
try {
stm = conn.createStatement();
rs= stm.executeQuery(sql);
while(rs.next()) {
//Extract ResultSet here as per needed logic
}
} catch (SQLException e) {
// Your control comes here if query is wrong , put a break point at below line & examine value of rs
e.printStackTrace();
}finally {
// Close resources not needed after this method call like - result sets , statements & connection
}
}
Firstly statement won't execute, so next execution is depends on how you are going to handle that exception. So, if exception comes and if you handle also there will be null in ResultSet because no value assigned to it.

SQL Command to search from Java program

I am attempting to allow keyboard input from my Java Project to search for a Car License number (VARCHAR), from my database. I am getting an error in my tester class about SQL syntax error. What would be the correct procedure so that when I search for a license it will display that license. Thanks in advance
public Car getCar(String searchLicense) {
Car foundCar = new Car();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
statement = conn.createStatement();
resultSet = statement.executeQuery(
"select * from eflow.registration.cLicense where="+searchLicense);
while (resultSet.next()) {
foundCar = new Car(resultSet.getInt("cID"), resultSet.getString("cLicense"),
resultSet.getInt("cJourneys"), resultSet.getString("cUsername"),
resultSet.getString("cPassword").toString());
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return foundCar;
}
You missing single quote and column name also..
resultSet = statement.executeQuery(
"select * from eflow.registration.cLicense where cLicenseName='"+searchLicense+"'");
Better solution,try this..
resultSet = statement.executeQuery(
"select * from eflow.registration.cLicense where cLicenseName like '%"+searchLicense+"%'");
The direct problem you're talking about it that you are missing quotation on your query, since it is a string. so what #Dakoda suggested in the comments should solve it.
however, the bigger issue here is that you are vulnerable to SQL injection, as you are allowing user input into your query. If I'll put input like xxx' or 'a' ='a I'll be able to fetch your entire database.
You should use parameterized query to protect yourself

invalid column index error in java while fetching data from oracle 10g database. Cant figure out whats wrong

Code snippet:
On a button click, actionevent will be called
public void actionPerformed(ActionEvent e)
{
Function f = new Function();
Function is a nested class which i have used to establish the connection with the database.
The code snippet for function class is also provided in the end.
ResultSet rs = null;
String Cid ="cust_id";
String Pno="cust_phone";
String cat="cust_cat";
String start_date="st_date";
String Adv_amt="adv";
String Adv_end="end_date";
String Address="addr";
t2 is the Textfield name which i have used to get entry of customer name. I want to use this customer name as a PK to fetch all the other data about that customer from DB.
rs=f.find(t2.getText());
try{
if(rs.next())
{
t1.setText(rs.getString("cust_id"));
t3.setText(rs.getString("cust_phone"));
t4.setText(rs.getString("cust_cat"));
t5.setText(rs.getString("st_date"));
t6.setText(rs.getString("adv"));
t7.setText(rs.getString("end_date"));
t8.setText(rs.getString("addr"));
}
else
JOptionPane.showMessageDialog(null,"No data for this name");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
Here is the code snippet for nested class Function which is inside the main class:
class Function{
Connection con=null;
ResultSet rs= null;
PreparedStatement ps = null;
public ResultSet find(String s)
{
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#Localhost:1521:xe","system","qwerty");
ps= con.prepareStatement("Select * from gkkdb where cust_name='?'");
ps.setString(1,s);
rs= ps.executeQuery();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return rs;
}
}
Please help figure out the problem.
Don't put the parameter placeholder ? in single quotes.
This:
ps = con.prepareStatement("Select * from gkkdb where cust_name='?'");
should be
ps = con.prepareStatement("Select * from gkkdb where cust_name = ?");
The ? is not recognized as a placeholder if you enclose it in single quotes.
Sorting out the bind variable will fix your immediate issue.
You should explicitly specify what columns you want selected and that way you'll only get what you need (someone might add a BLOB column later) and you'll get them in the right order (someone might change the table create script before running on another DB instance, although you are looking up the columns by name, a different order would only impact if you were using positional indexes).
Ditto on the other answer re: bind variables (i.e. no quotes)
Plus, "select * from" is never a good idea, ask your DBA.
Obviously your code is for example, but you should make sure you free up any resources (Connection, Statement, ResultSet) as soon as they are done with. Use Java 7 try-with-resources.

Why won't my query run properly? When ever I pass a string variable through the executeQuery method I get an error

There is an error on the line that says ps = stmt.executeQuery();....the error says method executeQuery in interface Statement cannot be applied to given types;
required: String
found: no arguments
reason: actual and formal argument lists differ in length
But whenever I pass a String through that line I get an error saying java.sql.SQLException:Method 'executeQuery(String)' not allowed on prepared statement...
This method is for a button that adds all the Integer values in a column of SQL table.
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String SQL = "SELECT SUM(PRICE) FROM MENU";
stmt = con.prepareStatement(SQL);
ps = stmt.executeQuery();
if(ps.next()) {
String total = ps.getString("SUM(PRICE)");
textTotalCost.setText(total);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(null, err);
}
}
Column name is must while getting a data
Thanks
Updated following the question change
There is no column name explicitly specified for the calculated column SUM(PRICE) in your SQL statement. It would hardly ever actually be "SUM(PRICE)". Try naming your column. Also prepareStatement is useful when passing parameters. Simple Select does not need it:
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String SQL = "SELECT SUM(PRICE) As PRICE_TOTAL FROM MENU";
Statement stmt = con.createStatement();
ResultSet ps = stmt.executeQuery(SQL);
if(ps.next()) {
String total = ps.getString("PRICE_TOTAL");
textTotalCost.setText(total);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(null, err);
}
}
or access the value by column index rather than name:
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String SQL = "SELECT SUM(PRICE) FROM MENU";
Statement stmt = con.createStatement();
ResultSet ps = stmt.executeQuery(SQL);
if(ps.next()) {
String total = ps.getString(0);
textTotalCost.setText(total);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(null, err);
}
}
I don't fully understand your description but I think you are trying to assign the PreparedStatement created in
stmt = con.prepareStatement(SQL)
to a variable of type Statement (stmt) and that's causing the error. The line of code above works because PreparedStatement is an extension (or implementation) of Statement but
ps = stmt.executeQuery();
fails because the class Statement doesn't have an executeQuery method without parameters, PreparedStatement does.
#Y.B.'s solution and the rest of recommendations are good (the alias for sum(price) or getting the value by column index) if it's ok using a regular Statement. The alternative is changing the type of stmt to PreparedStatement in your original code.

How to assign a Value taken from the database to a label?

I need to assign a string taken by a query from the database to a Jlabel. I tried many methods but failed. How can i do it?
try{
String sql="SELECT MAX(allocationID) FROM allocation where unit='"+ dept + " ' ";
pst=conn.prepareStatement(sql);
String x= (pst.execute());
}
catch(Exception e){
}
Need to study the steps to connect to the database in java First db steps
Get the resultset from the statment by calling ResultSet rs = pst.execute();
Iterate through the list of rows by using the resultset object.
After that assign the value to the JLabel.
You just made several errors in your tiny program, take a look at the code below as an example:
// your way of using prepared statement is wrong.
// use like this
String sql="SELECT MAX(allocationID) FROM allocation where unit=?;";
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
// assign values to the variables in the query string
ps.setString(1, dept);
// execute the query
ResultSet rst = ps.executeQuery();
// parse the result set to get the value
// You'd better do some check here to ensure you get the right result
rst.next();
String x = rst.getInt(1) + "";
ps.close();
conn.close();
}
Have a look at the article if you are interested:https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html

Categories

Resources