开发者

jdbc4 - how to insert money type?

开发者 https://www.devze.com 2023-03-30 18:59 出处:网络
I faced an interesting problem as... I have MSSQL (2005) table A which contains money type column; the thing is I want to 开发者_运维技巧insert value to this column with T-SQL procedure call from Java

I faced an interesting problem as... I have MSSQL (2005) table A which contains money type column; the thing is I want to 开发者_运维技巧insert value to this column with T-SQL procedure call from Java code but I am not pretty sure which Java type should I use to prepare statement for this column to insert value? I couldn't find any example so maybe you can share some helpful snippets.

Any useful comment is appreciated


Couldn't you just use a double (or maybe float, but probably not)? Also, what are you gaining by using MONEY in your database? I've found DECIMAL to be much more reliable and flexible - for some background see Bad habits to kick : choosing the wrong data type and Performance / Storage Comparisons : MONEY vs. DECIMAL (sorry for missing images).


OK... things I could figure out is NOT TO USE money type directly just because the jdbc4 connector PrepareSatement does not contain setMoney etc so I want to share some walk around... Of course, it is not the final code way but still...

So

  • A) Money class from here to get string as $00.00 with displayAsDollars method

  • B) create mssql procedure with code like a

    create procedure aschema.test @a varchar(10)
    AS
    BEGIN
    
    DECLARE @b money    
    SET @b=CAST @a AS MONEY
    
    --todo: insert next...
    
    END;
    
  • C) So the proc call is quite simple as

    Money m=new Money("12.99");
    
    callableStatement = (SQLServerCallableStatement) connection.prepareCall(
                            "{call "+
                            DATABASE_NAME+
                            "."+
                            SCHEMA_NAME+
                            ".test(?)}");
    callableStatement.setString(1,m.displayAsDollarsCorrectly());
    callableStatement.executeUpdate();
    

    //...

As I was saying it is not the final code decision but a temp conception which may be helpful as well if you really need to use money type in your old mssql database. At least it was a temp answer in my case :)

I hope it will be helpful for someone :)

Good luck

0

精彩评论

暂无评论...
验证码 换一张
取 消