java例外:从字符串转换日期和/或时间

时间:2012-03-18 16:46:25

标签: java sql-server jdbc

执行以下代码获取会话错误消息时。任何帮助或建议真的很感激。

import java.sql.* ;
import java.util.logging.*;

class check
{
 public static void main( String args[] )
 {
  try
  {
      // Load the database driver
      Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" ) ;

      // Get a connection to the database
      Connection conn = DriverManager.getConnection( "jdbc:sqlserver://example.com:1433;user=sa;password=root;databaseName=fetcher") ;

      // 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() ) ;
      }

      // Prepare a statement
      String sql = "select top 5 ID, DN, Type, IPaddress, Date, CheckDate from DATA where (date >= getdate() -2 )";

      Statement cs = conn.createStatement();
      // Execute the query
      ResultSet rs = cs.executeQuery(sql) ;


      // Loop through the result set
      int i = 0;
      while( rs.next() ) {


         String row_id = rs.getString("ID");
         String row_dn = rs.getString("DN");
         int row_type = rs.getInt("Type");
         String row_ipaddress = rs.getString("IPaddress");
         Date row_date = rs.getDate("Date");
         Date row_checkdate = rs.getDate("CheckDate");
         iupdateQuery(i, row_id, row_dn, row_type, row_ipaddress,row_date, row_checkdate);
         i++;
         }

      // Close the result set, statement and the connection
      rs.close() ;
      cs.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 ) ;
  }
 }

 private static void iupdateQuery(int i, String row_id, String row_dn, int row_type, String row_ipaddress, Date row_date, Date row_checkdate) {
                String srow_id = row_id;
                String srow_dn = row_dn;
                int    srow_type = row_type;
                String srow_ipaddress = row_ipaddress;
                Date srow_date = row_date;
                Date srow_checkdate = row_checkdate;

                String squery =  "SET IDENTITY_INSERT dbo.DATA ON";
                String insertquery = "insert into DATA(ID, DN, Type, IPaddress, CheckDate) values ('"+ srow_id +"','"+ srow_dn +"','"+ srow_type +"','"+ srow_checkdate +"')"; 

                // debug
                String filename = "C:\\test\\output.txt";


                try {
                 // Load the database driver
                 Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" ) ;

                // Get a connection to the database
               Connection dbconn = DriverManager.getConnection( "jdbc:sqlserver://localhost:1433;user=sa;password=root;databaseName=fetcher") ;

                        Statement es2 = dbconn.createStatement();
                        es2.executeUpdate(squery);   
                        int data_check = es2.executeUpdate(insertquery);
                        dbconn.commit();
                        if (data_check != 0)
                         {
                         System.out.println("Inserted: " + insertquery); 
                          }
                         else
                         {

                        String updatequery = "update DATA set DN='"+ srow_dn +"',Type='"+ srow_type +"',IPaddress='"+ srow_ipaddress +"',CheckDate='"+ srow_checkdate +"' where ID='"+ srow_id +"' "; 

                        // es2.executeUpdate(updatequery);
                        dbconn.commit();
                        System.out.println("Update: " + updatequery); 
                         }


                } catch (Exception e) {
                    // debug out output this way
                    System.err.println("Mysql Statement Error: " + insertquery);             
                    e.printStackTrace();

                }
        }


}

错误:

   com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converti
    ng date and/or time from character string.
            at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError
    (SQLServerException.java:197)
            at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServ
    erStatement.java:1493)
            at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQ
    LServerStatement.java:775)
            at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute
    (SQLServerStatement.java:676)
            at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575)
            at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLSe
    rverConnection.java:1400)
            at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLSer
    verStatement.java:179)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLS
erverStatement.java:154)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeUpdate(SQLServ
erStatement.java:633)
        at syncdata.iupdateQuery(syncdata.java:129)
        at syncdata.main(syncdata.java:60)

2 个答案:

答案 0 :(得分:1)

您的代码阅读起来有些棘手(在SQLserver数据库中报告错误为“Mysql语句错误”方面很奇怪) - 但基本上这两行都应该改变:

String insertquery = "insert into DATA(ID, DN, Type, IPaddress, CheckDate) values ('"
     + srow_id +"','"+ srow_dn +"','"+ srow_type +"','"+ srow_checkdate +"')"; 

...
String updatequery = "update DATA set DN='"+ srow_dn +"',Type='"+ 
         srow_type +"',IPaddress='"+ srow_ipaddress +"',CheckDate='"+ 
         srow_checkdate +"' where ID='"+ srow_id +"' ";

你应该在SQL语句中包含这样的值。相反,您应该使用PreparedStatement并为值设置参数。有很多好处:

  • 避免SQL injection attacks
  • 它可以避免转换错误,就像你现在获得的错误一样
  • 它使您的代码(SQL)与您的数据分开
  • 在查询执行计划缓存方面也可以带来性能优势

有关详细信息,请参阅JDBC tutorial

答案 1 :(得分:0)

问题似乎就在这条线上......

String updatequery = "update DATA set DN='"+ srow_dn +"',Type='"+ srow_type +"',IPaddress='"+ srow_ipaddress +"',CheckDate='"+ srow_checkdate +"' where ID='"+ srow_id +"' "; 

此处row_checkdate的类型为Date,您要将其转换为String ..

在您的数据库尝试将此String转换为Date时,内部会抛出此错误。