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)
Related
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 ?
When I run all my JUnit tests, which uses a MS SQL Server database, I'm getting the following error:
java.sql.SQLException: Could not find database ID X, name 'database_name'. The database may be offline. Wait a few minutes and try again.
or sometimes the java.sql.Connection object is closed unexpectedly.
I got rid of the problem when I turned AUTO CLOSE setting to OFF, right after database creation:
CREATE DATABASE TEST123;
ALTER DATABASE [TEST123] SET AUTO_CLOSE OFF WITH NO_WAIT;
Check it out: Worst Practice: Allowing AutoClose on SQL Server Databases
I have recently incorporated the Apache Tomcat JDBC Connection Pool to my application (using MySQL DB). I tried using Apache DBCP before, but didn't like its results, and the tomcat implementation seemed to fit my needs even though I run a standalone java application and don't use tomcat at all.
Recently, I encountered a huge performance problem when executing batch (aka bulk ) insert queries.
I have a flow in which I insert ~2500 records to a table in a batched fashion. It takes forever when using the jdbc connection pool, compared to a few seconds when reverting back to opening a connection for each query (no pooling).
I wrote a small application that inserts 30 rows to the same table. It takes 12 seconds when pooling, and ~ 800 millis when not pooling.
Prior to using the connection pool, I used com.mysql.jdbc.jdbc2.optional.MysqlDataSource as my DataSource. The connection was configured with the following line:
dataSource.setRewriteBatchedStatements(true);
I'm quite sure that this is the core difference between the two approaches, but couldn't find an equivalent parameter in jdbc-pool.
MySql JDBC driver does not support batch operations. RewriteBatchedStatement is the best that you can get. Here the code from mysql PreparedStatement.java:
try {
statementBegins();
clearWarnings();
if (!this.batchHasPlainStatements && this.connection.getRewriteBatchedStatements()) {
if (canRewriteAsMultiValueInsertAtSqlLevel()) {
return executeBatchedInserts(batchTimeout);
}
if (this.connection.versionMeetsMinimum(4, 1, 0) && !this.batchHasPlainStatements && this.batchedArgs != null
&& this.batchedArgs.size() > 3 /* cost of option setting rt-wise */) {
return executePreparedBatchAsMultiStatement(batchTimeout);
}
}
return executeBatchSerially(batchTimeout);
} finally {
this.statementExecuting.set(false);
clearBatch();
}
It is one of the reason why I do not like MySql and prefer Postgres
EDIT:
You should combine connection pool, batch operation, and RewriteBatchedStatement option. You can set RewriteBatchedStatement option through jdbc url parameter: jdbc:mysql://localhost:3307/mydb?rewriteBatchedStatements=true
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
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.