I am a new for JSP and I dont know any information about connection of oracle with JSP can anyone help me step by step?
You have to look at JDBC for Oracle. Using Java of course, not JSP.
This is a very basic Database class I used to use for very little projects.
public class Database {
private String driverName = "oracle.jdbc.driver.OracleDriver";
private Connection conn;
public static Hashtable errors = null;
public Database(String serverName, String portNumber, String serviceName, String username, String password, String db) {
errors = new Hashtable();
try {
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + serviceName;
Class.forName(driverName);
this.conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
System.out.println(e);
errors.put(db, e);
}
}
public Connection getConnection(){
return this.conn;
}
}
here is a sample of a query
Database db = new Database(......); // see Database class construct
try {
java.sql.Statement st = db.getConnection().createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM FOO");
while(rs.next()){
// your code
}
rs.close();
st.close();
} catch (SQLException ex) {
Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
}
hope this helps :)
Related
I'm using this openProxyConnection in the oracle method to create a proxy user to the database and used it with JDBC connection as below.
public static void openProxyConnection(OracleConnection conn, HttpUserDetails userDetails)
throws SQLException {
java.util.Properties prop = new java.util.Properties();
prop.put(OracleConnection.PROXY_USER_NAME,
userDetails.getUserName().toUpperCase()); //To uppercase needed for 11g compatibility
try {
// Open proxy connection for user
conn.openProxySession(OracleConnection.PROXYTYPE_USER_NAME, prop);
log.debug("Login proxy user: " + userDetails.getUserName());
try (PreparedStatement preparedStatement = conn
.prepareStatement("begin DBMS_APPLICATION_INFO.SET_CLIENT_INFO (?); end;")) {
preparedStatement.setString(1, userDetails.getClientIp());
preparedStatement.execute();
}
} catch (Exception e) {
throw new ProxyConnectionException("Error creating proxy connection", e);
}
}
#Override
public GetHostNameOutputDto getUserDetailsList(GetHostNameInputDto loginRequest, String spcNumber)
throws SQLException {
OracleCallableStatement statement = null;
OracleConnection connection = null;
GetHostNameOutputDto getHostNameOutputDto = new GetHostNameOutputDto();
try {
connection = (OracleConnection) dataSource.getConnection();
DbUtil.openProxyConnection(connection, httpUserDetails);
statement = (oracle.jdbc.OracleCallableStatement) connection
.prepareCall("begin ? := spc_login.get_host_name(?); end;");
statement.registerOutParameter(1, OracleTypes.VARCHAR);
statement.executeQuery();
...
As in the above example would I be able to get the proxy connection for JpaRepository? Something like below?
List<JobCode> jobCodeList = jobCodeRepository.findByLfunLbrFuncAndCorpCode("IN", "Y");
I am using Postman to test an ASP.Net web api 2 application that I created using I created using VS 2017.
It uses ADO.Net to call stored procedures. I tested the stored procedures and they work fine. I created a console app to test the methods and they work fine.
The URL that returns a model object works fine.
http://localhost:56224/api/profileandblog/getactiveuser/2020-03-03/DancinDan/32.211.50.62/1
The URL that returns a boolean does not. I get Error - 404.0 - Not Found
http://localhost:56224/api/profileandblog/validatelogin/2020-03-03/DancinDan/Morewealth1/32.211.50.62
Here is the dataaccesslayer.cs in my Models folder:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using GbngWebApi2.ADO_Utilities;
namespace GbngWebApi2.Models
{
public class DataAccessLayer
{
DatabaseFunctions dbFunc = new DatabaseFunctions();
public bool ValidateLogin(DateTime currentDateTime, string userName, string userPassword, string ipAddress)
{
bool returnedStatus = false;
try
{
dbFunc.OpenDB();
SqlCommand cmd = new SqlCommand("dbo.ValidateLogin", dbFunc.objConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#a_CurrentDateTime", currentDateTime);
cmd.Parameters.AddWithValue("#a_UserName", userName);
cmd.Parameters.AddWithValue("#a_UserPassword", userPassword);
cmd.Parameters.AddWithValue("#a_IpAddress", ipAddress);
// Set the OUT parameter.
cmd.Parameters.Add("#a_PasswordStatusSwitchOut", SqlDbType.Bit);
cmd.Parameters["#a_PasswordStatusSwitchOut"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
// Get the value from the OUT parameter.
// Cast to Boolean.
returnedStatus = (bool)cmd.Parameters["#a_PasswordStatusSwitchOut"].Value;
return returnedStatus;
}
catch (SqlException sqlex)
{
throw sqlex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbFunc.CloseDB();
}
}
public User GetActiveUser(DateTime currentDateTime, string userName, string ipAddress, int userId)
{
User user = new User();
SqlDataReader userDataReader = null;
try
{
dbFunc.OpenDB();
SqlCommand cmd = new SqlCommand("dbo.GetActiveUser", dbFunc.objConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#a_CurrentDateTime", currentDateTime);
cmd.Parameters.AddWithValue("#a_UserName", userName);
cmd.Parameters.AddWithValue("#a_IpAddress", ipAddress);
cmd.Parameters.AddWithValue("#a_UserId", userId);
userDataReader = cmd.ExecuteReader();
while (userDataReader.Read())
{
user.UserId = Convert.ToInt32(userDataReader["UserId"]);
user.UserName = userDataReader["UserName"].ToString();
user.ActiveSwitch = Convert.ToInt32(userDataReader["ActiveSwitch"]);
user.ApiAccessSwitch = Convert.ToInt32(userDataReader["ApiAccessSwitch"]);
user.AdminSwitch = Convert.ToInt32(userDataReader["AdminSwitch"]);
user.BlogAuthorSwitch = Convert.ToInt32(userDataReader["BlogAuthorSwitch"]);
user.BlogUserName = userDataReader["BlogUserName"].ToString();
user.IpAddress = userDataReader["IpAddress"].ToString();
user.IpAddressUsedForRegisteringCount = Convert.ToInt32(userDataReader["IpAddressUsedForRegisteringCount"]);
user.LoginCount = Convert.ToInt32(userDataReader["LoginCount"]);
user.ModifiedCount = Convert.ToInt32(userDataReader["ModifiedCount"]);
user.SuggestionCount = Convert.ToInt32(userDataReader["SuggestionCount"]);
user.SelectedForPublicViewSwitch = Convert.ToInt32(userDataReader["SelectedForPublicViewSwitch"]);
user.ModifiedDateTime = Convert.ToDateTime(userDataReader["ModifiedDateTime"]);
user.CreatedDateTime = Convert.ToDateTime(userDataReader["CreatedDateTime"]);
}
return user;
}
catch (SqlException sqlex)
{
throw sqlex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (userDataReader != null)
{
userDataReader.Close();
}
dbFunc.CloseDB();
}
}
}
}
Here is the WebApi2Controller:
using System;
using System.Web.Http;
using GbngWebApi2.Models;
namespace GbngWebApi2.Controllers
{
[RoutePrefix("api/profileandblog")]
public class WebApi2Controller : ApiController
{
DataAccessLayer dataaccesslayer = new DataAccessLayer();
[HttpGet]
[Route("validatelogin/{currentDateTime}/{userName}/{userPassword}/{ipAddress}")]
public bool ValidateLogin(DateTime currentDateTime, string userName, string userPassword, string ipAddress)
{
try
{
// Returns a boolean indicator of success or failure.
return dataaccesslayer.ValidateLogin(currentDateTime, userName, userPassword, ipAddress);
}
catch (Exception)
{
throw;
}
}
[HttpGet]
[Route("getactiveuser/{currentDateTime}/{userName}/{ipAddress}/{userId}")]
public User GetActiveUser(DateTime currentDateTime, string userName, string ipAddress, int userId)
{
try
{
// Returns the active "user" from the database.
return dataaccesslayer.GetActiveUser(currentDateTime, userName, ipAddress, userId);
}
catch (Exception)
{
throw;
}
}
}
}
From Nkosi: Add a slash at the end and it will work /32.211.50.62/
I have a Java EE web application. I am connecting database with JDBC and I am using JDBC connection pool. My application's main page is login page. After I enter the login page and wait for a while, I take this glassfish server(4.1.0) warning consistently.
Warning: RAR5035:Unexpected exception while destroying resource from
pool OraclePool. Exception message: Error while destroying resource
:IO Error: Socket read timed out
Even if I don't do any action on the page. When I monitore the statistics of the connection pool, NumConnCreated is increasing continuously. How can I solve the problem?. Thank you.
This is my managed bean class.
#ManagedBean
#SessionScoped
public class Login implements Serializable{
private String userName;
private String password;
private User user;
private #EJB DBRemote db;
public void test(){
String[] params1 = {"user","1234"};
int[] getParams = {Types.INTEGER,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR};
CallableStatement statement = db.run("TBL.USERLOGIN(?,?,?,?,?,?)", params1 , getParams);
try {
int isLogin = statement.getInt(3);
if (isLogin==1) {
String uName = statement.getString(4);
String uId = statement.getString(5);
user = new User(uId, uName, isLogin);
System.out.println("LOGGED IN " + uName + "\t" + uId);
}else{
String errMessage = statement.getString(6);
user = new User(errMessage,isLogin);
System.out.println("LOG IN FAILURE " + errMessage);
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}finally{
db.close();
FacesContext.getCurrentInstance().addMessage("infoback", new FacesMessage(FacesMessage.SEVERITY_INFO,
"TEST","Test Works"));
}
}
}
This my interface class
#Remote
public interface DBRemote {
CallableStatement run(String query, String[] setParams, int[] getParams);
void close();
String getErrorMessage();
String getSql();
}
This is my Stateless Bean class
#Stateless
public class DB implements DBRemote{
#Resource(mappedName = "pwresource")
private DataSource ds;
private String sql;
private String errorMessage;
private CallableStatement statement;
private Connection connection;
public DB() {
}
#Override
public CallableStatement run(String query, String[] setParams, int[] getParams){
sql = "{call " + query + "}";
int getParamIndex = setParams.length + 1;
try {
connection = ds.getConnection();
statement = connection.prepareCall(sql);
for (int i = 0; i < setParams.length; i++) {
statement.setString(i+1, setParams[i]);
}
for (int getParam : getParams) {
statement.registerOutParameter(getParamIndex, getParam);
getParamIndex++;
}
statement.execute();
}catch (SQLException ex) {
if (ex.getErrorCode()==17008) {
errorMessage = "Timeout";
}else{
errorMessage = "System Error";
}
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
close();
}
return statement;
}
#Override
public void close(){
try {
if (statement != null) {
statement.close();
}
if(connection != null){
connection.close();
}
errorMessage = null;
} catch (SQLException e) {
errorMessage = "Close Connection Error";
}
}
#Override
public String getErrorMessage() {
return errorMessage;
}
#Override
public String getSql() {
return sql;
}
}
I have solved my problem. My problem is because of the connection between connection pool and database. Database closes the connections automically because of the server and database in different networks caused timeout issue.
I am having this method
public List<Course> getCourses() throws InvalidCourseDataException {
ArrayList<Course> allCoursesFromDB = new ArrayList<>();
Connection dbConnection = null;
String getFromTableSQL = "SELECT * FROM courses";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
resultSet = statement.executeQuery(getFromTableSQL);
while (resultSet.next()) {
String courseCategory = resultSet.getString("course_category");
String courseTitle = resultSet.getString("course_title");
int courseId = resultSet.getInt("course_id");
Date startDate = resultSet.getTimestamp("starting_date");
Date endDate = resultSet.getDate("ending_date");
String description = resultSet.getString("description");
int teacherId = resultSet.getInt("teacher_id");
Course course = new Course(courseCategory, courseTitle, startDate, endDate);
course.setCourseId(courseId);
course.setTeacherId(teacherId);
course.setDescription(description);
addParticipantsIdToCourse(course);
allCoursesFromDB.add(course);
}
The getDBConnection() method is
private static Connection getDBConnection() {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
My problem is that resultSet.next() is returning only the first row from DB. I'am sure that I have multiple rows. I saw JDBC ResultSet is giving only one row although there are many rows in table? that question but it really doesn't answer my :)
I am sorry for the question. I found my mistake. ResultSet next() method is working fine, but I've changed its value in my addParticipantsIdToCourse(course) method :)
Here is the stack trace:
java.sql.SQLException
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:290)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:702)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:634)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:488)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:144)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:116)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:103)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:127)
at com.boeing.DBReader.Server.makeConnection(Server.java:85)
at com.boeing.DBReader.Server.<init>(Server.java:26)
at com.boeing.DBReader.Reader.main(Reader.java:13)
Caused by: java.lang.NullPointerException
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:395)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278)
... 11 more
Connection closed
And here is the code:
public class Server
{
private DataSource datasource;
public Server()
{
try
{
createConnectionToDatabase();
} catch (Exception e)
{
// TODO Auto-generated catch block
System.out.println("Exception:" + e.toString());
}
makeConnection();
}
private void createConnectionToDatabase() throws Exception
{
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("**");
p.setPassword("**");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1 from dual");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(600);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
datasource = new DataSource();
datasource.setPoolProperties(p);
}
private void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (Exception ignore) {
System.out.println("Could not close connection, WTF?");
}
}
}
private void makeConnection()
{
Connection con = null;
String queryString = "SQL QUERY GOES HERE ";
try {
System.out.println("Connection attempt");
con = datasource.getConnection();
System.out.println("Connection made no issues");
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
e.printStackTrace();
} finally {
closeConnection(con);
System.out.println("Connection closed");
}
}
I have the driver attached to the build path.. What am I doing wrong? This is set up without maven, and just a normal java project.
Thanks!
Not entirely sure from the stack trace, but this looks wrong:
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
You're setting the URL to connectionString, which is null.