2012-03-13 37 views
0

我正在使用以下代码更新数据库中的记录。Java数据库错误

import java.sql.* ; 

class JDBCUpdate 
{ 
public static void main(String args[]) 
{ 
     String DB_URL = "jdbc:mysql://localhost/mydatabase"; 
    try 
    { 

     Class.forName("com.mysql.jdbc.Driver") ; 



    // Database credentials 
    String USER = "user"; 
    String PASS = "pass"; 

     // Get a connection to the database 
     Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); 


     // Print all warnings 
     for(SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning()) 
     { 
      System.out.println("SQL Warning:") ; 
      System.out.println("State : " + warn.getSQLState() ) ; 
      System.out.println("Message: " + warn.getMessage() ) ; 
      System.out.println("Error : " + warn.getErrorCode()) ; 
     } 

     // Get a statement from the connection 
     Statement stmt = conn.createStatement() ; 

     // Execute the Update 
     int rows = stmt.executeUpdate("UPDATE people SET id = 9842 WHERE birthyear=3434") ; 

     // Print how many rows were modified 
     System.out.println(rows + " Rows modified") ; 

     // Close the statement and the connection 
     stmt.close() ; 
     conn.close() ; 
    } 
    catch(SQLException se) 
    { 
     System.out.println("SQL Exception:") ; 

     // Loop through the SQL Exceptions 
     while(se != null) 
     { 
      System.out.println("State : " + se.getSQLState() ) ; 
      System.out.println("Message: " + se.getMessage() ) ; 
      System.out.println("Error : " + se.getErrorCode()) ; 

      se = se.getNextException() ; 
     } 
    } 
    catch(Exception e) 
    { 
     System.out.println(e) ; 
    } 
} 
} 

在stmt.executeUpdate(),如果我尝试更新的文字或大于整数抛出错误以外的任何值的记录。有人能告诉我如何克服这个错误。

+1

_what_错误被抛出? – cdeszaq 2012-03-13 14:48:58

+0

请显示您的表格定义。 – 2012-03-13 14:55:27

回答

0

在stmt.executeUpdate()如果我尝试更新记录文本或任何 值以外的整数引发错误。有人可以告诉我如何克服这个错误 。

现在,看看你的UPDATE语句:

UPDATE people SET id = 9842 WHERE birthyear=3434 

我打赌是因为Id列是一个整数,因此在整场设置文本抛出异常。

+0

不,我试着用下面的方法改变名字列(UPDATE people SET id = 9842 WHERE name = fhbb) – user1092042 2012-03-13 14:47:21

+3

啊,那是因为fhbb需要用单引号括起来:'UPDATE people SET id = 9842 WHERE name = 'fhbb'' – Icarus 2012-03-13 14:49:04

+0

是的。这是正确的,谢谢。 – user1092042 2012-03-13 15:10:06