简体   繁体   中英

Conversion failed when converting date and/or time from character string

i want to insert the record in sql server . Table name and columns are specified in this code,

      String str_date=date;

      DateFormat formatter ; 

      formatter = new SimpleDateFormat("MM/dd/yyyy");

      date1 = (Date)formatter.parse(str_date);  

      System.out.println("Today is " +date1 );

     try{

      String query="INSERT INTO BULT_DATA " +
                "(ULDT_ID" +
                ",ULDT_DESC" +
                ",ULDT_DT" +
                ",ULDT_ULTH_ID" +
                ",ULDT_DATA_FILE" +
                ",ULDT_MAX_ROW_NO" +
                ",ULDT_REC_STS" +
                ",ULDT_CRE_USER_ID" +
                ",ULDT_CRE_DT" +
                ",ULDT_UPD_USER_ID" +
                ",ULDT_UPD_DT" +
                ",ULDT_APRV_USER_ID" +
                ",ULDT_APRV_DT)" +
                "VALUES ('"+
                uploadID+"','"+
                uploadDes+"','"+
                date1+"','" +
                templateID+"','"+
                dataFile+"','"+
                noRows+"','" +
                        "N','" +
                        "admin','" +
                        "2011-12-05 18:41:50.000','" +
                        "admin','" +
                        "2011-12-05 18:41:50.000','" +
                        "NULL','" +
                        "NULL')";


            System.out.println("query :: "+query);

        int stmnt= stmt.executeUpdate(query);

                 }catch (Exception e) {

        e.printStackTrace();
 }

but i got this exception

com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.

First, only American humans use MM-DD-YYYY format for dates - everyone/everything else, especially databases, uses the ISO format YYYY-MM-DD .

JDBC when used correctly will handle formatting your object into your SQL for you.

Thirdly (and this is minor), prefer stmt.execute() over stmt.executeUpdate() for inserts - an insert is not an update, it's an insert. Although, it will work using either.

Putting it all together, you get something like this (for example):

String sql = "insert into table (int_col, date_col, boolean_col, text_col)" +
   " values (?, ?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setObject(1, 7);
statement.setObject(2, new Date());
statement.setObject(3, true);
statement.setObject(4, "hello");
statement.execute();

Note:

  • the use of placeholders ? in the sql
  • the use of statement.setObject(n, object)
  • the absence of quotes around date and text placeholders

The JDBC driver will do all the necessary conversions and formatting for you for all "usual" java objects, especially enclosing values in quotes for you if quotes are required for that column/data type.

You can change your code around yourself to work in the way I've demonstrated here.

Use an ISO or ODBC date format for all values.
Or the legacy SQL Server yyymmdd hh:nn:ss

MM/dd/yyyy is not safe, neither are the the constants you gave for UPD_DT and ULDT_CRE_DT

'19980223 14:23:05'
{ts '1998-02-23 14:23:05'}
{d '1998-02-23'}
'1998-02-23T14:23:05'

And have you heard of SQL Injection, often caused by building SQL commands with string concatenation

your date1 object will be formatted using the standard toString() representation of java.lang.Date , which is unlikely to be compatible with the various date formats supported by your JDBC drivers.

Rather use another SimpleDateFormat object to format date1 into your SQL Server default date format before appending it to your query.

Also, do yourself a favour and read up on PreparedStatements and paramaterised queries; they really make this sort of stuff easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM