I am trying to use SQLServerBulkCopy for migrating data from PostgreSQL to MS-SQL Server. I am facing problem for non-English characters (Unicode). To store these data, in PostgreSQL text
datatype and for MS-SQL, nvarchar
is used.
This is the code snippet
public class MssqlBulkLoad {
public static void main(String args[]) throws SQLException {
String sql = "select id, data::varchar from test_data";
Connection pgConn = getPgConnection();
Statement pgStmt = pgConn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
pgStmt.setFetchSize(200);
Connection sqlServerConn = getSQLServerConnection();
SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(sqlServerConn);
bulkCopy.setBulkCopyOptions(options());
bulkCopy.setDestinationTableName("TEST_DATA2");
ResultSet pgResultSet = pgStmt.executeQuery(sql);
printMeta(pgResultSet);
bulkCopy.writeToServer(pgResultSet);
pgResultSet.close();
bulkCopy.close();
sqlServerConn.close();
pgStmt.close();
pgConn.close();
}
private static void printMeta(ResultSet pgResultSet) throws SQLException {
ResultSetMetaData rsmd = pgResultSet.getMetaData();
int c = rsmd.getColumnCount();
for (int i = 1; i <= c; i++) {
System.out.println(rsmd.getColumnType(i) + "\t" + rsmd.getColumnTypeName(i));
}
}
private static SQLServerBulkCopyOptions options() throws SQLException {
SQLServerBulkCopyOptions options = new SQLServerBulkCopyOptions();
options.setBulkCopyTimeout(60000);
options.setKeepIdentity(true);
options.setBatchSize(50);
return options;
}
}
The newly migrated data is in an unknown format, see below
But, the actual data should be as shown below.
In my Java code, to select data from PostgreSQL, I tried using simple select query, select * from test_data
but I am getting exception
com.microsoft.sqlserver.jdbc.SQLServerException: Data type other is not supported in bulk copy.
From this, it seems that when selecting data of text
datatype, the type of the column in ResultSet is Types.OTHER
. So, to avoid about mentioned exception, I case text type to varchar
, which returns types as Types.VARCHAR
.
I am using sqlserver-jdbc driver 7.0.0
Can someone help me with this.