Stop, restore and restart MS SQL server - java

I have a build deployed on my local and I am able to access the application using https://localhost:8443/dashboard. Now, as a part of my junits, I am supposed to take the backup of the database used by this application and restore it to its earlier state as the application inserts some data across multiple tables as a part of the tests. So, I need to restore the DB before the tests run. Now, I am able to backup and restore it using java program (junit) but the problem is coming when the server is running. It says DB is already in use and can't restore. Is there a way to disconnect the db connection (user) used in the application, do the restoration and then connect back again so that I don't have to shutdown the server and start it manually again.
Using commands similar to following -
BACKUP DATABASE [Store] TO DISK = N'"+backuppath+"' WITH NOFORMAT, NOINIT,
NAME = 'demodb-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10";
And
RESTORE DATABASE ["+dbName+"] FROM DISK='"+database_backup_location+"' WITH
REPLACE, MOVE '"+mdfLogicalName+"' TO
'"+getPropertyByKey("databse.dbfiles.location")+mdfLogicalName+".mdf', MOVE
'"+ldfLogicalName+"' TO
'"+getPropertyByKey("databse.dbfiles.location")+ldfLogicalName+".ldf';
Error that I am getting -
org.springframework.jdbc.UncategorizedSQLException: StatementCallback;
uncategorized SQLException for SQL [RESTORE DATABASE ....error code [3101];
Exclusive access could not be obtained because the database is in use.; nested
exception is com.microsoft.sqlserver.jdbc.SQLServerException: Exclusive access
could not be obtained because the database is in use.

I am already using the BACKUP and RESTORE commands. RESTORE command
gives error because the database is in use.
I've already answered, you just need to set your database offline this way:
alter database myDB set offline with rollback immediate
Doing this you'll disconnect all the users from your db and now you can make a RESTORE

You need to do below steps :
Backup the database
BACKUP DATABASE [Store] TO DISK = N'"+backuppath+"' WITH NOFORMAT, NOINIT,
NAME = 'demodb-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10";
Kill existing connections
USE master;
DECLARE #kill varchar(8000); SET #kill = '';
SELECT #kill = #kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE dbid = db_id('Store')
EXEC(#kill);
Then run the restore script.

Related

processBuilder failing to load data on different host?

On host 'A' I start a transaction by inserting values to a table in DB. As soon as I insert, I call processBuilder to refresh host 'B' which in-turn should load the updated values from same DB table to cache. But the values are not getting loaded.
Is there any relation between processBuilder and transaction? Because the transaction is yet to complete on the host from where I am calling processBuilder.
I tried fetching values from DB before calling processBuilder on host 'A' and it is returning the values which was recently inserted (result set returns 10 rows) where as on host 'B' which is calling same select statement return 9 rows.
"as soon as I insert" red flag.
Yes, there is a relationship between the transaction and processBuilder. If the transaction is not committed, then all other sessions will not be able to see the changes. If you're used to programming in a DB app environment where autocommit is enabled and switch to a DB app environment where autocommit is disabled, then you are likely to run across this kind of problem.

DBLinks ORA-24778: cannot open connections

I have a stored procedure which opens the cursor to fetch the data from remote databse
Cursor crs1 is select distinct ID FROM xxxx#link where xxxx and ID = v_id;
Open crs1;
loop fetch crs1 into v_N_ID;
exit when crs1%notfound;
end loop;
This week we started getting this ORA-24778: cannot open connections error. After restarting the websphere server and call the stored procedure it works 2 or 3 times and then again it fails.
We are using XA and the OPEN_LINKS_PER_INSTANCE is set to default 4.
I dont find any answers based on the discussion here
ORA-24778: cannot open connections
How to fix this issue?

How to check number of active connections in mysql database using java and close it

I want to check the number of active open connections in mysql database using java and close it.
I tried using query only
SHOW STATUS LIKE 'threads_connected';
With this can anyone tell me how to find and close the connection. I know when a database connection is established we need to close it immediately but for some other requirement i want to know active connections list and delete that list.
Any idea please suggest
I pulled aout the strings used bei HeidiSQL
First for getting a list with active connections(Processes):
SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, LEFT(INFO, 51200) AS Info FROM information_schema.PROCESSLIST
The for deleting a processes:
KILL {The ID of the Process};
It would probably be enough to SELECT only the ID of the Process but with that query you get all Information needed.

How to configure Play Framework 2 to make a readonly database connection?

I am developing an application which would fetch data from an Oracle database. It is a reporting app, no insert, update, delete is required. I know that I can set privilege for the database user to only select. But can I configure the database connection in Play application to make it readonly? I would hate to make any change or create a new user for my app. I understand that Play Framework 2.1.3 uses BoneCp for data connectivity.
Edit
I am using Java version of Play!
java.sql.Connection has a method called setReadOnly, which does exactly what it says:
DB.withConnection{ implicit connection =>
connection.setReadOnly(true)
...
}
An exception will be thrown when trying to execute write queries. You could also wrap DB.withConnection to clean things up across the application:
def withReadOnlyConnection[T](block: => T): T = {
DB.withConnection{ implicit connection =>
connection.setReadOnly(true)
block(connection)
}
}
And use it just like DB.withConnection:
def listThings: List[Stuff] = {
withReadOnlyConnection{ implicit connection =>
SQL(...)
}
}
Of course, it would still be better to have a separate database user with the limited permissions.
Edit:
For Java it's not going to be as pretty, but the same thing applies:
Connection connection = DB.getConnection();
connection.setReadOnly(true);
// Do something with this connection.

how to start a sql server agent job from java code

I have few SQL Server Agent Jobs running in my project. The jobs run perfectly as scheduled, no issues.
But now I need to be able to start these jobs from the front end (Like on a click of button or so).
How can I do it ?
Do these jobs behave just like a functions ?
You can do this with any db connector I've tried--here are a couple examples...
Using CallableStatement:
Connection rConn = //however you get your connection...
CallableStatement cs = rConn.prepareCall("EXEC dbo.sp_start_job N'your job name'");
boolean checkvar = cs.execute();
Alternatively, if you use a jdbc template:
jdbcTemp = //however you get your template...
jdbcTemp.update("EXEC msdb.dbo.sp_start_job N'" + procName + "'");
Also, you will likely need to adjust the permissions of the msdb in order for this to work. Your account needs to either be a sysadmin or have the SQLAgentOperatorRole role. To set this in SQL Server Management, go to Security under your db engine, expand logins, right click on the account you will use and select properties. Under Server Roles you can grant sysadmin, or under User Mapping check msdb, then select TargetServersRole and SQLAgentOperatorRole from the list below.
hth
you can call it by using the sp_startjob proc
example
EXEC msdb.dbo.sp_start_job N'MyJobName';

Categories