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;";
Related
The db2 database is called panth01
the sqlserver database is called proof
As you can see in the code, I made a single query, to extract language in db2 and language in sqlserver.
The problem that in Db2 the column is called LANGUAGE
In sqlserver the column is called LINGUA
In db2 the LANGUAGE column has two words "en"
in SqlServer the LINGUA column has three corners "eng"
I made the query:
//DB2
private static final String DB_DRIVER_DB2 = "com.ibm.db2.jcc.DB2Driver";
private static final String DB_CONNECTION_DB2 = "jdbc:db2://10.12.230.83:50000/PANTH01";
private static final String DB_USER_DB2 = "finance";
private static final String DB_PASSWORD_DB2 = "finance";
//SQLSERVER
private static final String DB_DRIVER_SQLSERVER = "net.sourceforge.jtds.jdbc.Driver";
private static final String DB_CONNECTION_SQLSERVER = "jdbc:jtds:sqlserver://10.65.21.15:1433;DatabaseName=PROVA";
private static final String DB_USER_SQLSERVER = "sa";
private static final String DB_PASSWORD_SQLSERVER = "sa";
public void selectTHERACLASS_HDR_THERACLASS_HDR_NLS() throws Exception {
//DB2_inizio
Connection dbConnection = null;
Statement statement = null;
//DB2_fine
//SqlServer_inzio
Connection dbConnectionSqlServer = null;
Statement statementSqlServer = null;
//SqlServer_fine
//Query SqlServer and db2
String query = "select PANTH01.THERA.CLASS_HDR.LANGUAGE, PROVA.DIZIOPT.LINGUA from PANTH01.THERA.CLASS_HDR JOIN PROVA.DIZIOPT.LINGUA ON PANTH01.THERA.CLASS_HDR.LANGUAGE = PROVA.DIZIOPT.LINGUA";
try {
//DB2_inizio
dbConnection = getConnectionDb2();
statement = dbConnection.createStatement();
//DB2_fine
//sqlserver_inizio
dbConnectionSqlServer = getConnectionSqlServer();
statementSqlServer = dbConnectionSqlServer.createStatement();
ResultSet rSqlServer = statementSqlServer.executeQuery(query);
//sqlserver_inizio_fine
while (rSqlServer.next()) {
String language = rSqlServer.getString("LANGUAGE");
String lingua = rSqlServer.getString("LINGUA");
System.out.println("LANGUAGE: " + language);
System.out.println("LINGUA: " + lingua);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null && statementSqlServer != null) {
statement.close();
statementSqlServer.close();
}
if (dbConnection != null && dbConnectionSqlServer != null) {
dbConnection.close();
dbConnectionSqlServer.close();
}
}
}
Output
Invalid object name 'PANTH01.THERA.CLASS_HDR'
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) {}
}
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.
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?
Does Selenium supports Database testing? If yes, how to do it?
A browser testing tool is not the right tool for database testing. For that you use a regular unit testing framework, as all database access is within your serverside code.
Unless of course your database access is browser based, in which case you have bigger problems than choosing a test framework.
If you want to connect to a database, use DB connection APIs, for example JDBC for Java.
Consider using TestPlan which allows you to combine Web UI testing with custom Java test units. Those test units can then access your DB and use it in the UI scripts.
For database testing youcan make a connection to the database using JDBC driver and then can fetch data or execute sql queries to perform content testing.
For example-
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
//Now here you can test wheather the data you have entered through User Interface gets entered into the database
--Write the code for comparision
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
//end finally try
}
//end try
}
//end main
}
//end