Solved

JDBC VARCHAR problem

Posted on 2002-05-09
4
543 Views
Last Modified: 2008-03-03
I am inserting data into an SQL Server database from a coarse-grained EJB. When a string is inserted into a VARCHAR field in the database, the string is taking up the full length of the VARCHAR field, rather than just the length of the string - any ideas?

This problem does not occur with my fine-grained EJBs which use stored procedures to insert data.

Thanks in advance.
0
Comment
Question by:joannape
4 Comments
 
LVL 3

Expert Comment

by:jerelw
ID: 6998659
Use ResultSetMetaData to get your max sizes, and then truncate your varchar to to 'fit' in your field.

Or use static longs to limit your data to the size of your fields.
0
 
LVL 4

Accepted Solution

by:
Neutron earned 200 total points
ID: 7000687
hi joannape :-)

jerelw's solution is usable, only I wouldn't use ResultSetMetaData because you have to make a select on the table to get access to it. Instead I would use DatabaseMetaData to retrieve column information. Here is the snippet:

-------snip-------8<-------
...
public static final int TYPE = 0;
public static final int TYPE_NAME = 1;
public static final int PRECISION = 2;
public static final int SCALE = 3;
...

public HashMap getColumnDefinitions( Connection con, String catalog, String schema, String table )
{
    HashMap columns = new HashMap();
   
    String columnName;
    Object[] columnDefinition;
   
    try
    {
        ResultSet rs = con.getMetaData().getColumns( catalog, schema, table, "%" );
       
        while (rs.next())
        {
            columnName = rs.getString( 4 ).toLowerCase();
           
            columnDefinition = new Object[4];
            columnDefinition[TYPE] = new Integer( rs.getInt( 5 ) );
            columnDefinition[TYPE_NAME] = rs.getString( 6 );
            columnDefinition[PRECISION] = new Integer( rs.getInt( 7 ) );
            columnDefinition[SCALE] = new Integer( rs.getInt( 9 ) );
           
            columns.put( columnName, columnDefinition );
        }
    }
    catch( SQLException e )
    {
        System.out.println( "Cannot execute DatabaseMetaData#getColumns method for table:"+table+" Message:"+e.getMessage() );
    }
   
    return columns;
}

public String truncateIfNecessary( String column, String value, HashMap columns )
{
    Object[] def = columns.get( column );
   
    int type = ((Integer)def[PRECISION]).intValue();
    int precision = ((Integer)def[PRECISION]).intValue();
   
    if (type==java.sql.Types.VARCHAR)
    {
        if (value.length() > precision)
        {
            value = value.substring( 0, precision );
        }
    }
   
    return value;
}
-------snip-------8<-------

Now when you need the column information you can have code like this:

...
HashMap columns = getColumnDefinitions( someConnection, null, "MYSCHEMA", "MYTABLE" );

preparedStatement.setString( index, truncateIfNecessary( "COLUMNNAME", sValue, columns ) );
...

-

If you don't need all the columns like it is presented here, you can put in the hashmap only VARCHAR fields and then you need only the PRECISION value stored and not the Object[4].

You could also have one hashmap for all the tables, so you can use tableName+"."+columnName as key for hashmap entries.

'hope this helps

Greetings,
    </ntr> :)
0
 
LVL 35

Expert Comment

by:girionis
ID: 8741083
No comment has been added lately, so it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question is:

- points to Neutron

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

girionis
Cleanup Volunteer
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
eclipse shortcuts 9 45
Apps blocked by Java 9 60
Arrays.asList  VS  ArrayList 4 44
couple of eclipse 5 21
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now