for Ex:
class sample {
public static void main(String a[]) {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:orcl", "", "");
String str = "Slect * from EMP";
Statement st = con.createStatement();
try {
st.executeUpdate("select * from EMP"); //gives us Exception } catch(SQLException ex) { // I want actuval code here.......... //CODE here............
}//catch}//try}//main}//class
As others have pointed out: executeUpdate() can not be used to run queries.
If you are looking for a way to execute statement without knowing what they do, you should have a look at the execute() method.
http://download.oracle.com/javase/6/docs/api/java/sql/Statement.html#execute%28java.lang.String%29
The returned boolean will tell you if it returned a result or just update counts. You can then use getResultSet() to obtain the result or getUpdateCount() to get number of affected rows.
Note that a statement is allowed to return more than one result and/or udpate count. See the example in getMoreResults().
the below code exlpains that the execute update statement gives exception in the case of
JdbcOdbcDriver but not in case of OracleDriver
so it is not always necesarry that select statement will give exception in executeUpdate("Select * ...");
but it depends on the Drive we register in DriverManager.registerDriver(Driver ob);
some Driver May give Exception while some will not
but the answer to your question is you should not use executeUpdate("Sel..")
for select Statement even if doesn't give Exception read the below code and and comment you will understand better
import java.sql.*;
import sun.jdbc.odbc.*;
import oracle.jdbc.driver.*;
public class MyDb {
public static void main(String args[]) throws Exception {
//drive is oracle.jdbc.driver.OracleDriver;
OracleDriver od = new OracleDriver();
DriverManager.registerDriver(od);
Connection conn;
conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "system", "system");
Statement stm = conn.createStatement();
int val = stm.executeUpdate("select * from mylog");
System.out.println(val);
//output for above code is 10 actually the table had 15 rows
//but when table had 7 rows output was 7 ,when number of rows where 9 output was 9
//but when the number of row in table were more than or equal to 10 the out put was 10
//so actually it is no meaning to use select statement within executeQuery
//even if it doesn't give exception
//driver is sun.jdbc.odbc.JdbcOdbcDriver;
JdbcOdbcDriver od2 = new JdbcOdbcDriver();
DriverManager.registerDriver(od2);
Connection conn2 = DriverManager.getConnection("jdbc:odbc:swap", "system", "system");
Statement stm2 = conn2.createStatement();
int val2 = stm2.executeUpdate("select * from mylog");
//while this code gives exception
//Exception in thread "main" java.sql.SQLException: No row count was produced
// at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(Unknown Source)
// at MyDb.main(MyDb.java:19)
System.out.println(val2);
}
}
executeUpdate is intended for statements that modifies data (update, insert). This is why you get an exception /by the way why do you want to use executeUpdate here?)
String str = "Slect * from EMP";
Should be
String str = "Select * from EMP";
as well.
Related
results.next() is false, !results.next() in the while loop prints ResultSet closed
I've tried EVERYTHING. from doing Class.forName() to connection.setAutoCommit(false) nothing's working :/
public static void main(String[] args) throws Exception {
String query = "SELECT * FROM StudentInfo";
String url;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection(url);
ps = connection.prepareStatement(query);
results = ps.executeQuery();
while (results.next()) {
print(results.getString("nameID"));
}
} catch (SQLException e) {
print(e.getMessage());
}
}
just prints out BUILD SUCCESSFUL without printing any of my data
The first thing to consider is to make sure that the table isn't empty.
Class.forName isn't even assigned to anything.
connection.setAutoCommit(false) is irrelevant here as that's more of a transaction detail. You don't need to worry about that for a query this simple.
I'd try running a query that you know works first. Maybe your connection isn't even correct or possibly null, thus never really executing the query. That's probably why your resultset is closed.
I also hope print() is from System.out or something that will actually print.
I have the following problem. I have the method which use the query to check if there is any reservation for given place in time from Start to End to check if the user can book this place in given time then returns Ture of False. My problem is that every time my ResultSet is equal to null. I do debug step by step and all variables are properly passed. With the debugger, I found that after passing 4 arguments (2nd-time start date) the fifth is skipped and myRs value remains null. Also, the 4th argument after passing is underlined with the green line but no communication is displayed. I am using Netbeans. I have no idea whats going on. Here goes my DBUtil method code:
public boolean doesBookExist(int number, Date start, Date end) throws Exception {
boolean result = false;
Connection myConn = null;
PreparedStatement myStmt = null;
ResultSet myRs = null;
try {
// get a connection
myConn = dataSource.getConnection();
// create sql for validation
String sqlValidate = "SELECT * FROM `rezerwacje_miejsc`"
+ " WHERE `NR_MIEJSCA`=?"
+ " AND (`START` BETWEEN ? AND ?"
+ " OR KONIEC` BETWEEN ? AND ?)";
myStmt = myConn.prepareStatement(sqlValidate);
myStmt.setInt(1, number);
myStmt.setDate(2, new java.sql.Date(start.getTime()));
myStmt.setDate(3, new java.sql.Date(end.getTime()));
myStmt.setDate(4, new java.sql.Date(start.getTime()));
myStmt.setDate(5, new java.sql.Date(end.getTime()));
// execute query
myRs = myStmt.executeQuery(sqlValidate);
// check if there was a match
result = myRs.next();
return result;
} finally {
// close JDBC objects
close(myConn, myStmt, myRs);
}
This is incorrect:
myRs = myStmt.executeQuery(sqlValidate);
It should be just:
myRs = myStmt.executeQuery();
The version of executeQuery accepting a string is a holdover from Statement (API design problem). You want the one without parameters, which is provided by PreparedStatement.
There's also a typo in the query that I assume must just be in the question, not the real code: You have mis-matched backticks (you have one after KONIEC but not before it).
I am new to Java and JDBC.
I am trying to get a double value from a database through JDBC and make a global variable equal to that value. Here's what I did.
public class Console {
String sql;
Statement stmt;
Connection conn;
ResultSet rs;
//Category Total
public static double num;
public Console(){
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database?autoReconnect=true&useSSL=false","user","password");
stmt = conn.createStatement();
System.out.println("Connected database successfully...");
sql = "SELECT sum(a) FROM table";
while(rs.next()) {
rs = stmt.executeQuery(sql);
num = rs.getDouble("sum(a)");
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
System.out.println(num);
}
}
When I run the program it prints 0.0 although the actual value is not.
You need to get your result set prior to the while loop, and then iterate through it
rs = stmt.executeQuery(...);
while (rs.next()) {
// and process your results row by row here...
}
Otherwise (as you've discovered) your rs variable is unset
Your result set won't contain sum(a) as a column name. You can get the result positionally (e.g. getInt() can take an index integer) or rename your result column (e.g. select sum(a) as sum FROM table) and reference it like that.
You haven't intialized the ResultSet with executing the query. Then you can loop the result set.
sql = "SELECT sum(a) FROM table";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
num = rs.getDouble("sum(a)");
}
You have been getting the results in the loop, but you have to do it before reach the loop.
You are getting 0.0 because of the behavior of JDBC driver.
From java doc
Returns: the column value; if the value is SQL NULL, the value
returned is 0
To know that last read value was null from Resultset, you can use method rs.wasNull() method. it will return true if the last column value read was SQL NULL and false otherwise.
It's good practice to assign a column alias to calculated results like sum(a) and retrieve the values using that alias.
Also good practice is to use Java's try-with-resources.
The try-with-resources statement ensures that each resource is closed at the end of the statement.
Also, if your SQL statement would return NULL, e.g. in case the table is empty or no rows apply to the conditions in your WHERE clause, the ResultSet.getDouble method will return the value 0.
sql = "SELECT sum(a) AS sum_a FROM table"; // assign alias sum_a to the expression sum(a)
try( ResultSet rs = stmt.executeQuery( sql ) ) { // get a resultset object in a try-with-resources statement, to auto-close it at the end
rs.next( ); // for the query you have, checking if there's a next row is actually not necessary; there's always a result for your query
num = rs.getDouble("sum_a"); // retrieve the column value by its alias
} // rs will be closed for you at this point
I'm trying to print the returned value of a MySQL stored function from the JDBC code which is as follows (I am using MySQL Server 5.7.13):
package jdbc;
import java.sql.DriverManager;
import java.sql.*;
import java.util.Scanner;
public class CallableStatementsCallingFunctions {
public static void main(String... syrt)
{
try
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
System.out.println("Error(class): "+ e);
}
try
{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/collablestatement","root","mysql") ;
CallableStatement cs = conn.prepareCall("{call ?:=getBalance1(?)}");
String s = new Scanner(System.in).nextLine();
cs.registerOutParameter(1,Types.INTEGER);
cs.setInt(2,Integer.parseInt(s));
cs.execute();
System.out.println("Account number :" + cs.getInt(1));
conn.close();
}
catch(SQLException e)
{
System.out.println("Error(SQL) : "+e);
}
}
catch(Exception e)
{
System.out.println("Error(Fro outer try) : "+ e);
}
}
}
the stored function getBalance1(acno) is shown here
my code output is shown here
I am getting the output from the SQL command but in JDBC I am getting and SQLException saying that
parameter 1 is not an output parameter
I know that parameter 1 has been used as the placeholder of the returned value from the function in jdbc code. In prepareCall I also tried the syntax - {?:= call getBalance1(?)} , but even then getting the same Exception.
Why am I getting the exception?
I think I was getting the SQLException because I am using jdk1.8.xx in which the syntax of calling the stored function is different. The problem was solved by replacing statement
CallableStatement cs = conn.prepareCall("{call ?:=getBalance1(?)}");
in the code with
CallableStatement cs = conn.prepareCall("{? = call getBalance1(?)}");
The syntax of calling the function in the prepareCall() method as parameter is here.
getBalance1() is a MySQL FUNCTION, not a PROCEDURE, so I wouldn't expect using a JDBC CallableStatement to be applicable.
Even in your MySQL console test you are using
select getBalance1(103)
so you simply need to do the same thing in your Java code using a PreparedStatement:
PreparedStatement ps = conn.prepareStatement("select getBalance1(?)");
ps.setInt(1) = 103;
ResultSet rs = ps.executeQuery();
rs.next();
Double bal = rs.getDouble(1);
(It should be noted that since "balance" apparently refers to "money", REAL is not a good choice for the column type; details here.)
When we use the executeUpdate () method can not insert instructions to return ResultSet, such as a SELECT. I happen to have an update which to start a trigger, and the trigger have a command "Select * from table".
I could solve the problem by assigning this command to a variable as an example: "Select * from table " soon resultSet would be no problem for the JDBC executeUpdate.
The problem is that the system can work with triggers other integrated systems that have no domain and I can not change, so the option was to use the run command (), which as shown in the code image can I check if the return is a ResultSet ( return true). In the statement while discarding ResultSets generated in the trigger and getMoreResults returns me the number of rows affected by the Update, in the case of the frame in blue, using the statement returns the value 3, which is correct.
The problem is to use the PreparedStatement (red frame), where getUpdateCount is returning -1, but should return 3, which is the number of rows affected in the UPDATE.
Problem occurs in SQL Server 2012 database or 2008, it was not simulated with Oracle
Follows the code example with the existing trigger on the table that I'm doing update
I wonder if anyone knows why the return is different for getMoreResults.
Code Java
Trigger
public class TestarConexao {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:odbc:magnus;user=rh;password=rh;MARS_Connection=yes;", "rh", "rhk");
Statement stmt = conn.createStatement();
boolean is = stmt.execute("update Usu_teste set usu_codigo = 1 where usu_codigo = 1");
while (is) {
System.out.println("There is ResultSet: " + is);
is = stmt.getMoreResults();
}
System.out.println("UpdateCount with Statement: " + stmt.getUpdateCount());
PreparedStatement prepStmt = conn.prepareStatement("update Usu_teste set usu_codigo = 1 where usu_codigo = 1");
boolean isPrep = prepStmt.execute();
while (isPrep){
System.out.println("There is ResultSet: " + isPrep);
isPrep = prepStmt.getMoreResults();
}
System.out.println("UpdateCount with PreparedStatement: " +prepStmt.getUpdateCount());
}
}