java异常:从字符串转换日期和/或时间

java异常:从字符串转换日期和/或时间,java,sql-server,jdbc,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"

执行以下代码时,收到对话错误消息。任何帮助或建议都非常感谢

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)

您的代码阅读起来有些棘手(从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语句中包含这样的值。相反,您应该使用a并为值设置参数。有许多好处:

  • 它避免了
  • 它可以避免像现在这样的转换错误
  • 它将代码(SQL)与数据分开
  • 它在查询执行计划缓存方面也有性能优势

有关更多信息,请参阅。

问题似乎出在这一行

String updatequery = "update DATA set DN='"+ srow_dn +"',Type='"+ srow_type +"',IPaddress='"+ srow_ipaddress +"',CheckDate='"+ srow_checkdate +"' where ID='"+ srow_id +"' "; 
这里的
row\u checkdate
类型为
Date
,您正在将其转换为
字符串


在内部,当您的数据库尝试将此
字符串
转换为
日期
时,会抛出此错误。

检查SQL Server语句以获取日期值而不是字符值是否确实
rs.getDate(“日期”)
rs.getDate(“checkDate”)返回日期而不是字符串。Date和checkDate在数据库中的值类型是什么???它返回以下格式“2010-11-02 11:26:28.023”谢谢jon,当然会使用准备好的语句