gpt4 book ai didi

java - 如何将 Java 对象从 Java 代码转换为 SQL Server 表值参数

转载 作者:行者123 更新时间:2023-12-01 11:14:39 24 4
gpt4 key购买 nike

如何将 Java 对象转换为 SQL Server 表值参数?

public class User {
private int userId;
private String firstName;
private String lastName;
private String gender;
private String city;
}
CREATE TABLE TEST_USER]( 
[USER_ID] [int] NOT NULL,
[FIRST_NAME] [varchar](100) NULL,
[LAST_NAME] [varchar](100) NULL,
[GENDER] [varchar](10) NULL,
[CITY] [varchar](30) NULL,
PRIMARY KEY ( [USER_ID] )
);

CREATE TYPE USERTYPE AS TABLE (
USER_ID INTEGER NOT NULL ,
FIRST_NAME VARCHAR(100),
LAST_NAME VARCHAR(100),
GENDER VARCHAR(10),
CITY VARCHAR(30)
);

CREATE PROCEDURE SP_InsertUser @UserDetail USERTYPE READONLY
AS
BEGIN
SET NOCOUNT ON
INSERT INTO TEST_USER (USER_ID, FIRST_NAME, LAST_NAME, GENDER,CITY)
SELECT [USER_ID], [FIRST_NAME], [LAST_NAME],[GENDER],[CITY] FROM @UserDetail
END

我想将 User 类的对象转换为 (SQL Server)USERTYPE 表类型

最佳答案

在 JDBC 中使用以下逻辑:

SQLServerDataTable table = new SQLServerDataTable();
table.addColumnMetadata("USER_ID", Types.INTEGER);
table.addColumnMetadata("FIRST_NAME", Types.VARCHAR);
table.addColumnMetadata("LAST_NAME", Types.VARCHAR);
table.addColumnMetadata("GENDER", Types.VARCHAR);
table.addColumnMetadata("CITY", Types.VARCHAR);
table.addRow(
user.getUserId(),
user.getFirstName(),
user.getLastName(),
user.getGender(),
user.getCity()
);

try (SQLServerPreparedStatement stmt=
(SQLServerPreparedStatement) connection.prepareStatement(
"{ call SP_InsertUser (?) }")) {

stmt.setStructured(1, "dbo.usertype", table);
stmt.executeUpdate();
}

I have described this also in this blog post here .

关于java - 如何将 Java 对象从 Java 代码转换为 SQL Server 表值参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31981839/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com