2016-04-12 13 views
6

Ho una classe Student con i seguenti attributi:Come passare i parametri con valori di tabella dalla procedura memorizzata java a sql server?

Name, Department, Address, Grade. 

ora ho un ArrayList che contiene alcuni Student oggetti come questo,

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")); 

ho bisogno di passare questo arraylist al server SQL memorizzata procedura e inserire i dati dell'oggetto studente nella tabella. Come raggiungere al meglio questo in Java? Sono obbligato ad avere una procedura memorizzata.

Java versione 8, Sql Server 2014 se di qualsiasi utilizzo.

+0

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/f7377f1c-f235-4870-b4a9-eab041fbd7b5/is-tablevalued-parameters-available-in-java-jdbc? forum = sqldatabaseengine –

+0

Vedere anche https://blogs.technet.microsoft.com/dataplatforminsider/2016/04/04/preview-the-microsoft-jdbc-driver-6-0-for-sql-server/ e https://msdn.microsoft.com/en-us/library/mt651781.aspx Si noti che ciò richiede il driver di anteprima JDBC 6.0 (!) di SQL Server. –

risposta

9

Con gli input forniti da Mark Rotteveel sono riuscito a farlo. Grazie Marco, Sean grazie anche per l'input. Ecco il codice di lavoro per ognuno di voi che potrebbe trovare utile.

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(); 
+0

MS ha aggiunto questa funzione nella versione Apr-1 dell'anteprima 6.0 disponibile qui: https://www.microsoft.com/en-us/download/details.aspx?id=11774 – nirmal

+0

In alternativa al casting di PreparedStatement , è possibile passare l'istanza SQLServerDataTable al metodo PreparedStatement.setObject (int, Object). Questo ha funzionato per un tipo TVP definito nello schema dbo. – allenru

+0

SQLServerDataTable non è più disponibile come parte del download del driver. –

Problemi correlati