如何将表值参数从 java 传递到 sql server 存储过程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36575529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:37:42  来源:igfitidea点击:

How to pass Table-Valued parameters from java to sql server stored procedure?

javasql-serversql-server-2008jdbcmssql-jdbc

提问by Umakanth

I have a Studentclass with the following attributes:

我有一个Student具有以下属性的类:

Name, Department, Address, Grade. 

Now I have an ArrayListthat contains some Studentobjects like this,

现在我有一个ArrayList包含这样的Student对象,

List<Student> stuList = new ArrayList<Student>();
stuList.add(new Student("Tom","Comp", "123 street", "A"));
stuList.add(new Student("Jery","Comp", "456 street", "A+"));
stuList.add(new Student("Mac","Maths", "Dum Street", "B"));

I need to pass this arraylist to the sql server stored procedure and insert the student object data into the table. How to best achieve this in Java? I am required to have a stored procedure.

我需要将此数组列表传递给 sql server 存储过程并将学生对象数据插入表中。如何在 Java 中最好地实现这一目标?我需要有一个存储过程。

Java version 8, Sql Server 2014 if its of any use.

Java 版本 8、Sql Server 2014(如果有任何用途)。

回答by Umakanth

With the inputs provided by Mark RotteveelI was able to do it. Thanks Mark, Seanthanks for your input as well. Here is the working code for any of you that may find it useful.

通过Mark Rotteveel提供的输入,我能够做到。感谢 Mark,Sean 也感谢您的投入。这是您可能会发现它有用的任何人的工作代码。

String jdbcurl = "jdbc:sqlserver://TestServer:1433;DatabaseName=Student";
connection = DriverManager.getConnection(jdbcurl,"username","password");

SQLServerDataTable stuTypeDT = new SQLServerDataTable(); 
stuTypeDT.addColumnMetadata("StudentId", java.sql.Types.NUMERIC);
stuTypeDT.addColumnMetadata("Name", java.sql.Types.VARCHAR);
stuTypeDT.addColumnMetadata("Department", java.sql.Types.VARCHAR);
stuTypeDT.addColumnMetadata("Address", java.sql.Types.VARCHAR);

stuTypeDT.addRow("1","Tom", "A", "123 Street");
stuTypeDT.addRow("2","Jery", "B", "456 Street");
stuTypeDT.addRow("3","Mac", "C", "Vancour");

String ececStoredProc = "EXEC InsertStudentInfo ?";
SQLServerPreparedStatement pStmt = (SQLServerPreparedStatement)connection.prepareStatement(ececStoredProc);
pStmt.setStructured(1, "dbo.StudentInfoType", stuTypeDT);
pStmt.execute();