Java – com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the nvarchar value ‘123.0’ to data type int

javajdbcsqlsql server

This code below reads xls file and insert it to my test side. It also checks the database if the values in the xls file exist and does comparison with the page title.

The test fails and am giving the following error

com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the nvarchar value '123.0' to data type int.

the forceID in my database is int type and in this code is string but i converted in the following line

int q= (int)Double.parseDouble(forceID);

PLEASE Help!!! Am using SQL Server 2008 R2, Selenium WebDriver and Java

public void loginTest(String forceID,String user,String password)
    throws InterruptedException, IOException, SQLException{
  // test runmode of current dataset
  count++;
  if(!runmodes[count].equalsIgnoreCase("Y")) {
    skip = true;
    throw new SkipException ("Runmode for test set data is set to no"+ count);
  }
  APP_LOGS.debug("Excuting Login Test");
  APP_LOGS.debug(forceID +" -- "+ user +" -- "+ password +" -- ");

  openBrowser();
  driver.get(CONFIG.getProperty("testSiteName"));
  connToDatabase();


  // Check the db
  try{
    pstmt=conn.prepareCall("select * from Login where ForceID=? and Username=? and Password=?");
    pstmt.setString(1,forceID);
    pstmt.setString(2,user);
    pstmt.setString(3,password);
    rs=pstmt.executeQuery();
    valueFound =rs.next();
  }catch(Exception e){
    e.printStackTrace();
  }

  //log in to the app
  getObject("forceID").clear();
  int q= (int)Double.parseDouble(forceID);
  getObject("forceID").sendKeys(String.valueOf(q));
  //getObject("forceID").sendKeys(forceID);
  getObject("user").clear();
  getObject("user").sendKeys(user);
  getObject("password").clear();
  getObject("password").sendKeys(password);
  getObject("logOn").click();
  // get the title
  String actual_title=driver.getTitle();
  System.out.println(actual_title);
  System.out.println(valueFound);
  if (valueFound) {
    Assert.assertEquals(actual_title, "Dashboard");
  } else {
    Assert.assertEquals(actual_title, "Logon");
  }
}

Best Answer

You are comparing a string (the forceId parameter of you java method) to an integer in the database (the ForceID column in your database).

You need to convert forceID from a string to an integer in your java code and pass it to your prepared statment as an integer.

pstmt.setInt(1, (int)Double.parseDouble(fourceID));