java异常: converting date and/or time from character string

标签 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)

最佳答案

您的代码有点难以阅读(并且从 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了解更多信息。

关于java异常: converting date and/or time from character string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9760166/

相关文章:

postgresql - 连接到 jdbc :postgresql from Matlab 时找不到类异常 "java.time.temporal.TemporalField"

java - 如何?在 Java 中绘制自定义复合对象

java - 启用安全管理器时 URLClassLoader 发出的 ClassNotFoundException

sql - 查找列字符串值的组合

sql-server - 从一个 SQL Server Express 复制到另一个

java - SQuirreL配置: could not initial class org. apache.phoenix.jdbc.PhoenixDriver

java - 如何访问 Windows 8 中最近打开的文件?

java - 无法使用 Intellij 和 1.8 JDK 运行 fxml 应用程序

sql-server - 读取大 Excel 文件时收到 "not enough storage"错误

java - Spring BatchSqlUpdate 在一次失败后不执行 SQL 的其余部分