0

I have MSSQL procedure:

my_proc 

I get data from java

String sql = "exec my_proc '2016-01-01','2016-01-20','2016-01-01'";
stmt = connection.prepareStatement(sql);
rs = stmt.executeQuery();

and get all data fine!

but if I use

String msisdn, String startDate, String endDate

String sql = "exec my_proc ?,?,?";
        stmt = connection.prepareStatement(sql);
        stmt.setString(1, msisdn);
        stmt.setString(2, startDate);
        stmt.setString(3, endDate);
        rs = stmt.executeQuery();

I get error:

com.microsoft.sqlserver.jdbc.SQLServerException: Error converting data type varchar to datetime.

In procedure I have variables:

@Startdtin datetime,
@Enddtin datetime,
@msisdnin varchar(18)

I tried use

stmt.setTimestamp(2, startDate); //startDate - convert to Timestamp

and

 stmt.setDate(2, startDate); //startDate - convert to Date (sql and util)

It is not helped. How pass date to PreparedStatementcorrectly`?

user5620472
  • 2,722
  • 8
  • 44
  • 97

2 Answers2

0

Your startDate is of type String. So convert it into Date type.

java.util.Date myDate = new java.util.Date(startDate);
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());

-------------------------------
stmt.setDate(5, sqlDate);

Use CallableStatement to execute procedures.

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
0

Once corrected the format of your data you have to change the code.

To execute a procedure you need to use a CallableStatement, not a PreparedStatement.

If you have your date in string format, first convert it to Date in java using a SimpleDateFormat.

Than simply set it as Date on the callableStatement.

String dateString = ...;
Date date = ...;

myCallableStatement.setDate(1, date);
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • why String sql = "exec my_proc '2016-01-01','2016-01-20','2016-01-01'"; stmt = connection.prepareStatement(sql); rs = stmt.executeQuery(); work fine? – user5620472 Feb 12 '16 at 11:31
  • It depends from the type of database and the type of procedure. Procedures can accept parameters for both input and output (generally parameters named in the calls as IN or OUT). If your procedure doesn't use the parameters for output it should works also with a PreparedStatement, otherwise is not possible to take the results. Generaly is a best practice to use a CallableStatement when executing procedures and use a PreparedStatement only when executing standard queries – Davide Lorenzo MARINO Feb 12 '16 at 11:36