How to solve "ORA-00933 & ORA-00936" in SQL/Oracle? - sql

Im creating a student profile for our project in school and it's my first time to make this.
This is my query for my jTable (mouseclicked) I've created in netbeans
int row = jTable1.getSelectedRow();
String tc = jTable1.getModel().getValueAt(row, 0).toString();
try {
String query ="select * from CAREPOINT_STUDENT where NAME="+tc+" ";
pst= (OraclePreparedStatement) ungabelio1.prepareStatement(query);
rs = (OracleResultSet) pst.executeQuery();
if(rs.next()){
String NAME_ID = rs.getString("NAME");
String AGE_ID = rs.getString("AGE");
String ADDRESS_ID = rs.getString("ADDRESS");
String NUM_ID = rs.getString("NUM");
String COURSE_ID = rs.getString("COURSE");
String SPECIAL_ID = rs.getString("SPECIAL");
String SCHOOL_ID = rs.getString("SCHOOL");
String DOWNPAY_ID = rs.getString("DOWNPAY");
String DISCOUNT_ID = rs.getString("DISCOUNT");
String BALANCE_ID = rs.getString("BALANCE");
String REVSCHED_ID = rs.getString("REVSCHED");
String EMAIL_ID = rs.getString("EMAIL");
NAME.setText(NAME_ID);
AGE.setText(AGE_ID);
ADDRESS.setText(ADDRESS_ID);
NUM.setText(NUM_ID);
COURSE.setText(COURSE_ID);
SPECIAL.setText(SPECIAL_ID);
SCHOOL.setText(SCHOOL_ID);
DOWNPAY.setText(DOWNPAY_ID);
DISCOUNT.setText(DISCOUNT_ID);
BALANCE.setText(BALANCE_ID);
REVSCHED.setText(REVSCHED_ID);
EMAIL.setText(EMAIL_ID);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
When I run the program and tried to click the data (A Student Profile like name,age,school, etc..) that I created and printed inside the jtable (mouseclicked), I get this problem "ORA-00933: SQL command not properly ended"
Aside from that, I also have another problem which I created 2 jbutton called "DELETE" which means it will delete the data(Student profile) that I filled up and "UPDATE" which means to reedit the data(Student profile) that I filled up.
this is the query of my "DELETE" jbutton in netbeans
try {
String query;
query = "DELETE FROM CAREPOINT_STUDENT where NAME="+NAME.getText()+" ";
pst= (OraclePreparedStatement) ungabelio1.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Successfully deleted!");
fetch();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
and this is the query of my "UPDATE" jbutton in netbeans
try {
String query;
query = "update CAREPOINT_STUDENT set AGE=?,ADDRESS=?,NUM=?,COURSE=?,SPECIAL=?,SCHOOL=?,DOWNPAY=?,DISCOUNT=?,BALANCE=?,REVSCHED=?,EMAIL=? where NAME="+NAME.getText()+"";
pst= (OraclePreparedStatement) ungabelio1.prepareStatement(query);
pst.setString(1,AGE.getText());
pst.setString(2,ADDRESS.getText());
pst.setString(3, NUM.getText());
pst.setString(4, COURSE.getText());
pst.setString(5, SPECIAL.getText());
pst.setString(6, SCHOOL.getText());
pst.setString(7, DOWNPAY.getText());
pst.setString(8, DISCOUNT.getText());
pst.setString(9, BALANCE.getText());
pst.setString(10, REVSCHED.getText());
pst.setString(11, EMAIL.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Successfully updated!");
fetch();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
when I run the program and click those 2 buttons, I get the same problem "ORA-00936: missing expression"
I really appreciate and I hope that somebody would help me to fix this problem. So that I can gain some little knowledge about sql/oracle.
Sorry for my bad english.

Avoid concatenating parameters as strings; use prepared statements.
Otherwise you'll run in all kind of troubles, like escaping issues for special characters, SQL Injection, etc.
For example, a safer way of running your SQL statement could be:
String query = "select * from CAREPOINT_STUDENT where NAME = ?";
pst = (OraclePreparedStatement) ungabelio1.prepareStatement(query);
pst.setString(1, tc);
rs = (OracleResultSet) pst.executeQuery();
Note: Assembling a SQL statement as a string is still useful for cases when you want to do some dynamic SQL. Even then, use ? for parameters and apply them as shown above.

You may need some extra single quotes so you query will read:
select * from CAREPOINT_STUDENT where NAME='Entered name';
Adjust your code:
String query ="select * from CAREPOINT_STUDENT where NAME='"+tc+"' ";

Related

JSP SQL SERVER ResultSet always return empty

I'm doing two queries to a SQL Server database, the first query returns the Result Set with data, but the second query always returns the Result Set empty. If I do the query in the SQL SERVER, it does it well. I have tried to make another query: SELECT TOP 10 * FROM TABLE and always returns empty.
<%
String url,ssql;
int i,j,k;
int reg[]=new int[256];
try{
Class.forName("com.microsofto.sqlserver.jdbc.SQLServerDriver");
url="jdbc:sqlserver://localhost/;databaseName=acsc;user=user;password=1234";
Connection conn = DriverManager.getConnection(url);
Statement stc = conn.createStatement();
ssql="SELECT Nombre,max(Registro) FROM Tabla Group by Nombre order by Nombre";
ResultSet rsc= stc.executeQuery(ssql);
i=1;
while(rsc.next()){
reg[i]=rsc.getInt(2);
i++;
}
j=0;
do{
//ssql="SELECT * FROM Tabla Where Registro="+String.valueOf(reg[j]);
ssql="SELECT TOP 10 * FROM Tabla";
rsc= stc.executeQuery(ssql);
if(!(rsc.getRow()==0)){
out.println(rsc.getString(1)+" "+rsc.getString(2)+" "+rsc.getString(3));
}else{
out.println("vacio");
}
j++;
}while(j<i);
}catch(SQLException se){
out.println(se.toString());
}
%>
There are two problems with your code. The only one you need to fix is that you're not using Parameters in your SQL query. See
public static void executeStatement(Connection con) {
try(PreparedStatement pstmt = con.prepareStatement("SELECT LastName, FirstName FROM Person.Contact WHERE LastName = ?");) {
pstmt.setString(1, "Smith");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
}
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
}
Using an SQL Statement with Parameters
Thank you for your response and sorry for not having responded before.
I have tried using prepareStatement, but the ResultSet kept returning empty.
I finally found where I had the problem, if!(Rsc.getRow()==0)) always returned 0, even if the ResulSet had records.
I have removed that part of the program and I have placed while rsc.next() and it works correctly.
What is the second problem that my code has?
Thanks greetings

Searching SQL for specific CHAR

I have a database table were a column holds multiple strings. They are holding License Plate numbers. If I search for 1 il get the first registration it finds with a one. I want to set it so that I must enter the full string and if I don't it should say not found. Here is my code. I'm sure its just the SQL command that needs altering for this.
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 where cLicense like '%" + 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;
}
If you need the exact string, you will need to remove the '%' in the LIKE filter.
Your code should be:
cLicense like '" + searchLicense + "'
The '%' wildcard put before and after the parameter you have, enables you to search for any string containing the searchLicense value in the middle, without checks of what is before or after that string.
You should be using parameterized queries. Bobby Tables: A guide to preventing SQL injection
Then use = instead of like.
select * from eflow.registration where cLicense = #searchLicense

Inserting data through GUI into sql server

I'm able to execute sql statements by writing the sql codes (Insert etc) on Eclipse and it is being displayed into sql server correctly. Connection has been done. But what should I do when a user wants to add data through a GUI interface (text field) and the data need to get stored into the database automatically ??
my code in the ADD button, but i'm getting the Error: java.lang.NullPointerException ! Help please..
try {
String pid = ProductID.getText();
String sql = "insert into Products_tbl values (' " +pid + " ')";
// Running the sql query
rs = st.executeQuery(sql);
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Welcome");
}
else if (count > 1) {
JOptionPane.showMessageDialog(null,"Duplicate User Access Denied");
}
else {
JOptionPane.showMessageDialog(null, " User Not Found ");
}
}
catch (Exception ex) {
System.out.println("Error: " + ex);
}
1- Using (' " +pid + " ')" is not safe because SQL injection may occur. Use SqlParameters instead. Please check:
https://www.w3schools.com/sql/sql_injection.asp
2- I am pretty sure something is wrong with the line: rs = st.executeQuery(sql);
Here, I bet the value of st is null. Make sure that your connection variable is defined and set correctly and you created the statement like below:
st = connection.createStatement();
You can also try executeupdate(query) instead of executequery(query) like:
int flag = st.executeUpdate(query);
Ref: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29
3- Please use printStackTrace() method while printing the error in the catch blog, the error message would be more understandable.
System.out.println("Error: " + ex.printStackTrace());

get data from resultset after the execution of sql query in netbeans

I have created a table register in SQL with field username. In the JFrame when a user enters username there is a JButton for checking the username availability. For this I have used the code below:
String sqlstmt = "select username from register where username='" +
jTextField1.getText() + "'";
try {
st = con.prepareStatement(sqlstmt);
stmt = con.createStatement();
rs = st.executeQuery(sqlstmt);
if (rs.next()) {
JOptionPane.showMessageDialog(null,"found");
} else {
JOptionPane.showMessageDialog(null,"not found");
}
} catch(SQLException e) {
JOptionPane.showMessageDialog(null,"sql error");
}
when executing this query, it is seen that data is empty. Or if I put rs.getString("username") inside the if (rs.next), it shows the "sql error" message.
You're mixing Statements and PreparedStatements here.
The best approach here would probably be to use a PreparedStatement, which would take care of any funky characters from your input, and offer protection against SQL injection:
// SQL statement to prepare.
// Note the lack of single quotes (') in the parameter
String sqlstmt= "select username from register where username = ?";
// Prepare the statement
PreparedStatement st = con.prepareStatement(sqlstmt);
// Bind the argument
st.setString(1, jTextField1.getText());
// Execute
ResultSet rs = st.executeQuery();
// Rest of the code to handle results...
Note:
This example omits error handling (e.g., try-catch constructs) in favor of clarity.

JDBC returns an empty result set

ResultSet is empty although query should return whole table. Here is my code
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost","somonjon","sa");
con.setCatalog("ChatDBS");
Statement stmt = null;
String SQL = "SELECT * FROM Login_chat";
stmt = con.createStatement();
try{
System.out.println("trying execute query");
rs = stmt.executeQuery(SQL);
}
catch(SQLException ex){
ex.printStackTrace();
}
this is the error message:
trying execute query
com.microsoft.sqlserver.jdbc.SQLServerException: The result set has no current row.
P.S.
Okey guys I'm not sure is it important or not, but this codes is jButton1ActionPerformed event.
AFAIK, you are not suppose to get this exception unless you are doing some operation over ResultSet like rs.next();
Regarding the problem is concerned, there could be two scenarios
You are not pointing to right database (catalog)
You have not committed the transaction in the database.
You have to loop through rs.
String column1;
int column2;
while (rs.next()) {
column1 = rs.getString("nameColumn1");
column2 = rs.getInt("nameColumn2");
}
Ok, in
String SQL = "SELECT * FROM Login_chat";
You have to add a ";".
String SQL = "SELECT * FROM Login_chat;";
Try with that!