JDBC returns an empty result set - sql

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!

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

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

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

What is the error in this SQL update stament

I have the method that do update to data base table
but when I invoke it I have an exception "Incorrect syntax near '('."
Here is the method
internal Boolean update(int customerID,int followingID, string fullName, string idNumber, string address, string tel, string mobile1, string mobile2, string email, string customerComment, DateTime timeStamp)
{
string sqlStatment = "update customers set (followingID, fullName,idNumber,address,tel,mobile1,mobile2,email,customerComment,timeStamp) = (#followingID, #fullName,#idNumber,#address,#tel,#mobile1,#mobile2,#email,#customerComment,#timeStamp) where customerID=#customerID";
SqlConnection con = new SqlConnection();
con.ConnectionString = connection;
SqlCommand cmd = new SqlCommand(sqlStatment, con);
cmd.Parameters.AddWithValue("#customerID", customerID);
cmd.Parameters.AddWithValue("#followingID", followingID);
cmd.Parameters.AddWithValue("#fullName", fullName);
cmd.Parameters.AddWithValue("#idNumber", idNumber);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#tel", tel);
cmd.Parameters.AddWithValue("#mobile1", mobile1);
cmd.Parameters.AddWithValue("#mobile2", mobile2);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#customerComment", customerComment);
cmd.Parameters.AddWithValue("#timeStamp", timeStamp);
bool success = false;
try
{
con.Open();
cmd.ExecuteNonQuery();
success = true;
}
catch (Exception ex)
{
success = false;
//throw ex;
}
finally
{
con.Close();
}
return success;
}
and here is the database table columns
Your Syntax error is incorrect.Please refer the link for Update Query Syntax
update customers
set
followingID= #followingID,
fullName=#fullName,
idNumber=#idNumber,
address=#address,
tel=#tel,
mobile1=#mobile1,
mobile2=#mobile2,
email=#email,
customerComment=#customerComment,
timeStamp=#timeStamp
where customerID=#customerID
Your sql update statement is wrong. For more about update statement see
string sqlStatment = "update customers set followingID=#followingID,
fullName=#fullName,idNumber=#idNumber,address=#address,tel=#tel,
mobile1=#mobile1,mobile2=#mobile2,email=#email,
customerComment=#customerComment,timeStamp=#timeStamp
where customerID=#customerID";
UPDATE syntax is wrong..
Try
string sqlStatment = "UPDATE customers SET followingID= #followingID, fullName=#fullName, idNumber=#idNumber,address=#address,tel=#tel,mobile1=#mobile1,mobile2=#mobile2,email=#email,customerComment=#customerComment,timeStamp=#timeStamp WHERE customerID=#customerID"
Please see the Update statement syntax:
http://www.w3schools.com/sql/sql_update.asp
you cannot bulk update values in the table
Never seen an update statement like that - normally it'd be set followingid = #followingid, fullname = #fullname etc, etc
There is syntax error, update statement is used like this
update customers set followingID=#followingID,
fullName=#fullName,
idNumber=#idNumber,
address=#address,
tel=#tel,
mobile1=#mobile1,
mobile2=#mobile2,
email=#email,
customerComment=#customerComment,
timeStamp=#timeStamp
where customerID=#customerID

JDBC - Resultset is false

I have the following problem.
I'm using JDBC and doing a query. But the qry doesn't work. If I let print out rs.next() it returns false.
The same qry works on the SQL-Developer itself, just not in JDBC.
QRY:
ResultSet rs = stmt.executeQuery("select account_id, oper_type, new_value from action where account_id = 1");
//ResultSet rsAccount = stmt.executeQuery("select account_id from accounts");
System.out.println("Accounts Update");
System.out.println(rs.next());
if(rs.next() == true){
System.out.println("Not null");
}
Ok, I "solved" it. The problem was that my project tutor forgot to add commit; at the end of the sql file

How to get a single value back from query vs resultset

I have a JSP file that runs a select statement against an Oracle database.
All the examples I have seen use something like:
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery("Select * from data");
while(rs.next(){
String name=rs.getString("name");
String add=rs.getString("address");
out.println(name+" "+add);
}
I will never have more than one row coming back is there an alternative to ResultSet and a while loop to get at my returning single row of data?
I have used similar kind of thing to validate user login.
String sql = "SELECT * FROM login WHERE username=? AND password=?";
try {
PreparedStatement statement;
statement = connection.prepareStatement(sql);
statement.setString(1, "hardik"); // set input parameter 1
statement.setString(2, "welcome"); // set input parameter 2
ResultSet rs = statement.executeQuery();
if(rs.next()){
// fetch data from resultset
}
}catch(SQLException sqle){
sqle.printStackTrace();
}