Search code examples
javams-accessjdbcucanaccess

"invalid character value for cast" error on INSERT via UCanAccess


I'm getting the error

net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.6 data exception: invalid character value for cast

when I run this code:

 package aoa;
    import java.sql.*;
    public class Aoa {


        public static void main(String[] args)  {
             Connection cn;
      Statement st;
      ResultSet re;
      String ID ="username"; 
      String NAME="password";  


      try{

        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        cn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\MUHAMMAD SHAHAB\\STUD1.accdb");
        st = cn.createStatement();
       String q = "INSERT INTO STUD1 ([Id], [Address]) VALUES (?, ?)";
    PreparedStatement pst = cn.prepareStatement (q);
    pst.setString(1, "a");
    pst.setString(2, "b");
    pst.executeUpdate();

        System.out.println("inserted"); }    

        catch(ClassNotFoundException | SQLException e)
        {
          System.out.println(e);
        }

    }       
    }

What am I doing wrong?


Solution

  • You will get the error

    net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.6 data exception: invalid character value for cast

    if you try to assign a value to a numeric column via setString when the string value cannot be cast to a number. In your case, the [Id] column is almost certainly numeric, but

    pst.setString(1, "a");
    

    is trying to assign the value "a" to that column, and "a" cannot be converted to a number.