2011-01-21 70 views
0

防爆:SELECT查詢()代替的executeQuery()

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 
+0

不明確的問題 – 2011-01-21 06:46:28

+0

你得到的例外是什麼? – Nishant 2011-01-21 06:49:00

+0

異常是:java.sql.SQLExcetion,executeUpdate()返回多行。 – Kiran 2011-01-21 07:16:14

回答

1

executeUpdate旨在用於語句修改數據(更新,插入)。這就是爲什麼你會得到一個異常/用你想在這裏使用executeUpdate爲什麼呀?)

1
String str = "Slect * from EMP"; 

應該

String str = "Select * from EMP";

爲好。

3

正如其他人指出的:executeUpdate()不能用於運行查詢。

如果您正在尋找一種執行語句的方式而不知道他們在做什麼,那麼您應該查看execute()方法。
http://download.oracle.com/javase/6/docs/api/java/sql/Statement.html#execute%28java.lang.String%29

返回的布爾值將告訴您它是返回結果還是更新計數。然後可以使用getResultSet()獲取結果或getUpdateCount()來獲取受影響的行數。

請注意,允許語句返回多個結果和/或udpate計數。請參閱getMoreResults()中的示例。

1

下面的代碼exlpains的執行UPDATE語句給出例外的

JdbcOdbcDriver的情況下,但不是在OracleDriver
這樣情況下,它並不總是necesarry是select語句將給予例外executeUpdate("Select * ..."); 但要看在驅動器上,我們在DriverManager.registerDriver(Driver ob);

註冊一些驅動程序可能給異常,而有些則不會

但回答你的問題是你不應該使用的executeUpdate(「SEL ..」) 的SELECT語句,即使不給例外閱讀下面的代碼並和評論,你會更好地瞭解

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); 


} 

}