Would singleton database connection affect performance in a weblogic clustered environment? - database

I have a Java EE struts web application using a singleton database connection. In the past, there is only one weblogic server, but now, there are two weblogic servers in a cluster.
Session replication have been tested to be working in this cluster. The web application consist of a few links that will open up different forms for the user to fill in. Each form has a dynamic dropdownlist that will populate some values depending on which form is clicked. These dropdownlist values are retrieved from the oracle database.
One unique issue is that the first form that is clicked, might took around 2-5 seconds, and the second form clicked could take forever to load or more than 5 mins. I have checked the codes and happened to know that the issue lies when an attempt to call the one instance of the db connection. Could this be a deadlock?
public static synchronized DataSingleton getDataSingleton()
throws ApplicationException {
if (myDataSingleton == null) {
myDataSingleton = new DataSingleton();
}
return myDataSingleton;
}
Any help in explaining such a scenario would be appreciated.
Thank you
A sample read operation calling Singleton
String sql = "...";
DataSingleton myDataSingleton = DataSingleton.getDataSingleton();
conn = myDataSingleton.getConnection();
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
try {
pstmt.setString(1, userId);
ResultSet rs = pstmt.executeQuery();
try {
while (rs.next()) {
String group = rs.getString("mygroup");
}
} catch (SQLException rsEx) {
throw rsEx;
} finally {
rs.close();
}
} catch (SQLException psEx) {
throw psEx;
} finally {
pstmt.close();
}
} catch (SQLException connEx) {
throw connEx;
} finally {
conn.close();
}
The Singleton class
/**
* Private Constructor looking up for Server's Datasource through JNDI
*/
private DataSingleton() throws ApplicationException {
try {
Context ctx = new InitialContext();
SystemConstant mySystemConstant = SystemConstant
.getSystemConstant();
String fullJndiPath = mySystemConstant.getFullJndiPath();
ds = (DataSource) ctx.lookup(fullJndiPath);
} catch (NamingException ne) {
throw new ApplicationException(ne);
}
}
/**
* Singleton: To obtain only 1 instance throughout the system
*
* #return DataSingleton
*/
public static synchronized DataSingleton getDataSingleton()
throws ApplicationException {
if (myDataSingleton == null) {
myDataSingleton = new DataSingleton();
}
return myDataSingleton;
}
/**
* Fetching SQL Connection through Datasource
*
*/
public Connection getConnection() throws ApplicationException {
Connection conn = null;
try {
if (ds == null) {
}
conn = ds.getConnection();
} catch (SQLException sqlE) {
throw new ApplicationException(sqlE);
}
return conn;
}

It sounds like you may not be committing the transaction at the end of your use of the connection.
What's in DataSingleton - is it a database connection? Allowing multiple threads to access the same database connection is not going to work, for example once you have more than one user. Why don't you use a database connection pool, for example a DataSource?

Related

Script task in SSIS package is executing but not performing the action

I have the two SSIS packages which basically has two action like below
First it truncates the contents of the table and then it executes the script task like basically call an API and inserts the response in to the table
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public async void Main()
{
try
{
var sqlConn = new System.Data.SqlClient.SqlConnection();
ConnectionManager cm = Dts.Connections["SurplusMouse_ADONET"];
string serviceUrl = Dts.Variables["$Project::RM_ServiceUrl"].Value.ToString();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(serviceUrl);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
string APIUrl = string.Format(serviceUrl + "/gonogo");
var response = await client.GetAsync(APIUrl);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
try
{
sqlConn = (System.Data.SqlClient.SqlConnection)cm.AcquireConnection(Dts.Transaction);
const string query = #"INSERT INTO [dbo].[RM_Approved_Room_State]
(APPROVED_ROOM_STATEID,SOURCE_ROOMID,DEST_ROOMID,ENTITY_TYPEID)
SELECT id, sourceRoomRefId, destinationRoomRefId,entityRefId
FROM OPENJSON(#json)
WITH (
id int,
sourceRoomRefId int,
destinationRoomRefId int,
entityRefId int
) j;";
using (var sqlCmd = new System.Data.SqlClient.SqlCommand(query, sqlConn))
{
sqlCmd.Parameters.Add("#json", SqlDbType.NVarChar, -1).Value = result;
await sqlCmd.ExecuteNonQueryAsync();
}
}
catch (Exception ex)
{
Dts.TaskResult = (int)ScriptResults.Failure;
}
finally
{
if (sqlConn != null)
cm.ReleaseConnection(sqlConn);
}
}
}
catch (Exception ex)
{
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
} }
Similar to the above package I have another one which does more likely does insert records into different table the response from a different endpoint. When I execute the packages locally/ execute them separately after deploying it in to the server it works fine. But when I add them in to the SQL Server Agent Job like below and run them on a schedule
The Jobs run successfully and dont show any errors but I can see only one table with data from one package but the other one truncates the records but I dont think the script task is getting executed / I dont see any records inserted. I dont think there are any issues with access because when I run them seperate manually the data are getting inserted, Just when it is running on a schedule it is not working as expected. Any idea what could be happening here.. Any help is greatly appreciated

How to get data from sql DB in selenium webdriver?

How to get data from sql DB in selenium webdriver?
I would like to connect the selenium webdriver and sql DB, and need to get value from DB and to use in the selenium testNg framework.
Can any one provide me the right solution.
First you need to make connection with database by using following commands,
DriverManager.getConnection(URL of database, "username", "password" )
To get value, use following commands
ResultSet result = stmt.executeQuery(select * from tablename;);
You need to implement DB connector helper for connect, execute query and close data base connection. After than you can use result of query in your test.
Data Base connector depends on DB type(you need use specify DB driver).
Folowing java methodis illustrated connection with SQL Server Driver:
public java.sql.Connection getConnection() {
try {
Class.forName(SQLServerDriver.class.getName());
con = java.sql.DriverManager.getConnection(getConnectionUrl(), userName, password);
if (con != null) System.out.println("Connection Successful!");
} catch (Exception e) {}
return con;
}
and execute query:
public void executeQuery(String query) {
con = this.getConnection();
if (con != null) {
Statement st = null;
try {
st = con.createStatement();
st.executeQuery(query);
} catch (SQLException e) {}
}
this.closeConnection();
}
than close connection:
public void closeConnection() {
try {
if (con != null)
con.close();
con = null;
} catch (Exception e) {}
}

JDBC connection to linked server

I'm trying to connect from a Java application to a Linked Server I created with MSSQL Server.
The URL string is
jdbc:sqlserver://172.15.230.11
and the query is
SELECT * FROM OPENQUERY(172.15.230.11,'SELECT * FROM myTable WHERE
myCode = 345')
But when I run the program, this exception occurs:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'myUser'.
The actual code is here:
private static final String DB_URL_LOCAL = "jdbc:sqlserver://172.15.230.11";
private static final String DB_USERNAME_LOCAL = "myUser";
private static final String DB_PASSWORD_LOCAL = "myPassword";
private static final String DB_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static String SQL_READ = "SELECT * FROM OPENQUERY(172.15.230.11,'SELECT * FROM myTable WHERE myCode = 345')";
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(SQL_READ);
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static Connection getConnection(){
Connection connection = null;
Properties properties = new Properties();
try {
Class.forName(DB_CLASS);
properties.setProperty("characterEncoding", "utf-8");
properties.setProperty("user", DB_USERNAME_LOCAL);
properties.setProperty("password", DB_PASSWORD_LOCAL);
connection = DriverManager.getConnection(DB_URL_LOCAL, properties);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
First of all you have to make sure that you enable remote connections to MSSQLserver.
Then make sure you use a user in your connection wich has sufficient rights to query your schema.
Then make sure you provide the correct source to the JDBC driver:
dbsource= "jdbc:sqlserver://IP:1433;database=MY_SCHEMA";
Then make sure you load the correct JDBC driver and use the appropriate user and password
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dbCon = DriverManager.getConnection(dbsource, user, password);
On top of all that, if your database is using windows authentication, then you can use 'integratedSecurity':
dbsource= "jdbc:sqlserver://IP:1433;database=MY_SCHEMA;integratedSecurity=true;";

How to retrieve data using JDBC

I have been trying with the following code.
The connection is being made. But the resultSet is coming as empty (not null), whereas there are a couple of entries (2 fields each) in the database for the same.
It does not enter the while condition. I'm new to JDBC, please help!
My code is:
import java.sql.*;
public class JDBCTest123
{
public static void main(String[] args)
{
System.out.println("oracle Connect Example.");
Connection conn = null;
String url = "jdbc:oracle:thin:#127.0.0.1:1521:XE";
String driver = "oracle.jdbc.driver.OracleDriver";
String userName = "system";
String password = "mumpymamai";
Statement stmt = null;
String query = "select * from table1";
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
stmt = conn.createStatement();
System.out.println("Connected to the database");
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e)
{
e.printStackTrace();
}
}
}
And the output is:
oracle Connect Example.
Connected to the database
Disconnected from database
So few suggestions. I recommend to you use PreparedStatements which are more faster and safer.
PreparedStatement ps = null;
conn = DriverManager.getConnection(url, userName, password);
ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
// do some work
}
Second suggestion, call close() method in finally block, because application may crash and then your connection won't be closed. Finally block guarantees that will be always called.
Third suggestion if it doesn't work without Exception, probably you have empty table.

Windows Mobile C# application with database

I am writing a prototype application in Windows Mobile 6.5 device.
The objective of the app is to ask user for some inputs, collect data and store into local database and on a server.
I am done with creating GUI (in C#) of the application which takes all the necessary inputs from user.
Now, I need to insert this data into local DB and upload to server DB. Both the DBs will need to synced over HTTP when user selects to do so. I have not worked on databases much, except for writing some queries to fetch data from PostgreSQL in the past in Linux environment a few years ago.
So my question is, what is the easiest way to achieve the thing I am trying to? I don't need lot of features. The data is only strings and numbers (no files, multimedia stuff etc.)
What server I should install and run? What components should I use on client side?
Thanks
Ashish
To use database on windows mobile you need Microsoft SQL Server Compact 3.5 for Windows Mobile . http://www.microsoft.com/en-in/download/details.aspx?id=8831 . You can download and install from the link given. After installation C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Devices\wce500\armv4i will have all CAB files that needs to be installed to your mobile.
Install
sqlce.ppc.wce5.armv4i.CAB
sqlce.repl.ppc.wce5.armv4i.CAB
For more information on what to install refer http://msdn.microsoft.com/en-us/library/bb986876.aspx
I have written a small helper class to do all database transactions.
public class DataBaseHelper
{
public enum typeOfQuery
{
insert,
update,
delete,
getScalar,
getDataSet,
getDataTable
};
private string connectionString = Program.Connection;
public object ExecuteDatabaseQuery(string query, Dictionary<string, object> dictionary, typeOfQuery typeOfQuery)
{
try
{
using (SqlCeConnection oCon = new SqlCeConnection(connectionString))
{
oCon.Open();
string oSql = query;
using (SqlCeCommand oCmd = new SqlCeCommand(oSql, oCon))
{
oCmd.CommandType = CommandType.Text;
if (dictionary != null)
{
if (dictionary.Count != 0)
{
foreach (KeyValuePair<string, object> pair in dictionary)
{
if (pair.Value is DateTime)
oCmd.Parameters.Add(pair.Key, SqlDbType.DateTime).Value = pair.Value ?? DBNull.Value;
else if (pair.Value is bool || pair.Value is Boolean)
oCmd.Parameters.Add(pair.Key, SqlDbType.Bit).Value = pair.Value ?? DBNull.Value;
else
oCmd.Parameters.Add(pair.Key, SqlDbType.NVarChar).Value = pair.Value ?? DBNull.Value;
}
}
}
// check what type of query using the enums in the constants.cs file
if ((typeOfQuery == (typeOfQuery.insert)) || (typeOfQuery == typeOfQuery.update) ||
(typeOfQuery == typeOfQuery.delete))
{
return oCmd.ExecuteNonQuery();
}
else if (typeOfQuery == typeOfQuery.getDataSet)
{
SqlCeDataAdapter adapter = new SqlCeDataAdapter(oCmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
return dataSet;
}
else if (typeOfQuery == typeOfQuery.getDataTable)
{
SqlCeDataAdapter adapter = new SqlCeDataAdapter(oCmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
return dataSet.Tables[0];
}
else if (typeOfQuery == typeOfQuery.getScalar)
{
object returnValue = oCmd.ExecuteScalar();
if (returnValue == null)
{
return string.Empty;
}
else
return returnValue;
}
}
}
}
catch (SqlCeException ex)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
}
return false;
}
}
You can call this class as follows
string query = #"SELECT * FROM TABLE
WHERE COL1 = #COL1";
Dictionary<string, object> dictionaryToInsert = new Dictionary<string, object>();
dictionaryToInsert.Add("#COL1", Col1Value);
return (DataTable)new DataBaseHelper().ExecuteDatabaseQuery(query,
dictionaryToInsert, DataBaseHelper.typeOfQuery.getDataTable);
Similarly you can query database for other purposes also. use the enum and change the query and you will get the result.

Resources