Copying table to different database in MSSQL - java

I have condition where there are some table from one database (in mssql) which will be copied into another database. The copying time must be when a specific time, which will be given from application. In my case, I use Java programming. Is there any easiest way to do that?

Create a SQL Agent Job in MS SQL Server that copies your data from one database to the other. Then in your Java app connect to the MS SQL Server and start the SQL Server Agent Job.
Connection rConn = //Your Connection details
CallableStatement cs = rConn.prepareCall("EXECUTE dbo.sp_start_job N'your job name'");
boolean checkvar = cs.execute();
You will need to connect to the MSDB database and the account you connect with needs to be in the sysadmin role or the SQLAgentOperatorRole
You SQL statement in your job may look something like this:
INSERT INTO DestinationDatabseName.dbo.DestinationTable (ColumnNames)
SELECT YourColumns
FROM SourceDatabaseName.dbo.SourceTable

Related

Reference to database and/or server name in 'master.sys.geo_replication_links' is not supported in this version of SQL Server springboot

I want to execute sys.geo_replication_links to check if application is connected to primary or secondary database. however, I am not able to execute this command via spring boot.
I tried below approach but did not work.
#Query(nativeQuery = true, value = "SELECT partner_server FROM [master].sys.geo_replication_links")
public String getServerName();
I get below error message:
com.microsoft.sqlserver.jdbc.SQLServerException: Reference to database and/or server name in 'master.sys.geo_replication_links' is not supported in this version of SQL Server.
How can I call to master from my application database ? Is there a hack. I dont want to create a new connection just for one query, Is there a smarted approach ?

NamedParameterJdbcTemplate query and get generated PID from PostgreSQL

I'm using PostgreSQL and need to get the process identifier from PostgreSQL. Every running query in PostgreSQL has it's own PID which we can get via pg_stat_activity.
SELECT * FROM pg_catalog.pg_stat_activity;
This returns a PID, which we can use to stop executing queries in database using
SELECT pg_terminate_backend(<pid of the process>);
The application is Spring Boot / Java and I make some huge queries using NamedParameterJdbcTemplate. They can take a long time, and in some cases I need to terminate executing queries.
The question is how can I get the PID from the generated SQL query?
The PID is not related to a query, but to the connection (=session). Once you established a connection (through the JDBC driver), the PID for that connection (session) won't change.
So you could use:
select pg_backend_pid();
to obtain the the PID of your session at any time.
As you are most likely using a connetion pool, you need to make sure that calling pg_backend_pid() is done using the same connection that your NamedParameterTemplate uses (e.g. by putting both statements into a single transaction)

Can we send DB ResultSet in Java to another server so that rows will be fetched from that separate server?

I am running a query and checking if data exists, then I need to stream the 50000+ rows, but that needs to be done by another server. So I want to send the ResultSet object somehow to another server where the rows will be fetched. Is it possible?
I could just send SQL query to that another server. But will there be any security issues?

Sql Server data extraction (java jdbc): process hangs during retrieving rows

I need to extract data from a remote Sql server database. I am using the mssql jdbc driver.
I noticed that often dwhen retrieving rows from the database the process suddenly hangs, giving no errors. It remains simply stuck and no more rows are processed.
The code to read from the database is the following:
String connectionUrl = "jdbc:sqlserver://10.10.10.28:1433;databaseName=MYDB;user=MYUSER;password=MYPWD;selectMethod=direct;sendStringParametersAsUnicode=false;responseBuffering=adaptive;";
String query = "SELECT * FROM MYTABLE";
try (Connection sourceConnection = DriverManager.getConnection(connectionUrl);
Statement stmt = sourceConnection.createStatement(SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY, SQLServerResultSet.CONCUR_READ_ONLY) ) {
stmt.setFetchSize(100);
resultSet = stmt.executeQuery(query);
while (resultSet.next()) {
// Often, after retrieving some rows, process remains stuck here
}
}
Usually the connection is established correctly, some rows are fetched, than at some point the process can become stuck in retrieving the next rows batch, giving no errors and not processing any new row. This happens some times, other times it completes succesfully.
AFAIK the only reason I can see is that at some point a connection problem occurs with the remote machine, but shouldn't I be notified of this from the driver?
I am not sure how I should handle these type of situations...is there anything I can do on my side to let the process complete even if there is a temporary connection problem with the remote server (of course if the connection is not recoverable there is nothing I can do)?
As another test, instead of the java jdbc driver I've tried the bcp utility to extract data from the remote database and even with this native utility I can observe the same problem: sometimes it completes succesfully, other times it retrieves some rows (say 20000) and then becomes stuck, no errors and no more rows processed.

Problems logging into MSSQL server from Java

I am trying to connect to MSSQL server 2008 on my localhost, but I am getting Errors
WARNING: ConnectionID:2 Prelogin error: host 127.0.0.1 port 1434 Error reading prelogin response: Connection reset
this error repeats like 20 times very quickly, then i get
com.microsoft.sqlserver.jdbc.SQLServerException: Connection reset
I suspect this is some wrong configuration of server. I can connect to external servers with no issues. I can also connect via management studio with no problems.
Please help me, I am getting sick of this issue :|
1) TCP protocol for MSSQL 2008 is disabled by default. You need to enable it from SQL Configuration Manager (in the same [Start], Programs folder as MSSQL):
http://msdn.microsoft.com/en-us/library/ms190425%28v=sql.105%29.aspx
2) To use TCP connections (even on localhost!) you need to allow MSSQL in Windows Firewall:
http://technet.microsoft.com/en-us/library/cc646023.aspx
3) You don't necessarily need to use TCP/IP in order to access MSSQL:
http://msdn.microsoft.com/en-us/library/ms187892%28v=sql.105%29.aspx
'Hope that helps!
To connect to MSSQL Server from a Java application, you need to use the JDBC API. The JDBC API provides classes and methods that connect to the database, load the appropriate driver, send SQL queries, retrieve results etc.
HOW TO CONNECT TO THE DATABASE A ‘Connection’ object represents a connection with a database. To establish the connection, use the method ‘DriverManager.getConnection’. This method takes a string containing a URL which represents the database we are trying to connect to. Below is the sample code for establishing a connection:
private String DATABASE_URL = "jdbc:odbc:embedded_sql_app"; // establish connection to database
Connection connection = DriverManager.getConnection( DATABASE_URL,"sa","123" );
Detailed discussion about the Database URL and how to create it can be found in the resource provided at the end of this post.
QUERYING THE DATABASE The JDBC API provides three interfaces for sending SQL statements to the database, and corresponding methods in the ‘Connection’ interface create instances of them. 1. Statement - created by the ‘Connection.createStatement’ methods. A ‘Statement’ object is used for sending SQL statements with no parameters.
2. PreparedStatement - created by the ‘Connection.prepareStatement methods’. A ‘PreparedStatement’ object is used for precompiled SQL statements. These can take one or more parameters as input arguments (IN parameters).
3. CallableStatement - created by the ‘Connection.prepareCall’ methods. ‘CallableStatement’ objects are used to execute SQL stored procedures from Java database applications.
RETRIEVING THE RESULT A ‘ResultSet ‘is a Java object that contains the results of executing a SQL query. The data stored in a ‘ResultSet’ object is retrieved through a set of get methods that allows access to the various columns of the current row. The ‘ResultSet.next’ method is used to move to the next row of the ‘ResultSet’, making it the current row. The following code fragment executes a query that returns a collection of rows, with column ‘a’ as an ‘int’, column ‘b’ as a ‘String’, and column ‘c’ as a ‘float’:
java.sql.Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) { // retrieve and print the values for the current row
int i = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
System.out.println("ROW = " + i + " " + s + " " + f); }
This is just a brief introduction on how to interact with a database from Java. For more details on the items discussed above as well as information on passing parameters, executing stored procedures etc. please refer to the following resource: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html#Shahriar_N_Embedding_SQL_in_Java ) Here, you will also find information on how to interact with a database programmatically; i.e. without using SQL. Hope you find this useful.

Categories