Remote MySQL DB and eclipse - java

I am currently trying to implement a simple servlet that has to communicate with our database.
I have no real prior experience with databases, so I was wondering how I should I go about this? I have downloaded the mysql-connector-java-5.1.40 from dev.mysql.
Going over some of the directions on the web for setting up the connection, it seems to only be for local mysql, but what of remote? The remote's user and pass is demo/demo; of course I would also need to log into the the remote server with my credentials. How do I go about connecting to this remote db?
Edit: So I believe I successfully connected to the DB, at least I can see it in my eclipse under data sources and the tables are present (company and stock_prices), however my eclipse still says I have an unsuitable driver even though I do have one associated with it.

The proper way of consuming a database resources in a web container (or in an application server) is through the javax.sql.DataSource abstraction. So you should configure a data source in your container. For tomcat it's as simple as creating a file named context.xml in your war's META-INF folder with the following content (replace address and credentials with your own):
<Context>
<Resource name="jdbc/[YourDatabaseName]"
auth="Container"
type="javax.sql.DataSource"
username="[DatabaseUsername]"
password="[DatabasePassword]"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql:/[yourserver]:3306/[your-db]"
maxActive="20"
maxIdle="20"/>
</Context>
Then when you want to perform a DB operation:
you either look up the data source:
DataSource ds =(DataSource) new InitialContext().lookup("java:comp/env/jdbc[YourDatabaseName]");
or simply use dependency injection for managed components like servlets:
#Resource(name="jdbc/YourDataSource")
Datasource ds;
The you just get a connection from the datasource in order to execute statements to the database.
The DB driver can be put in one of two places:
the war's lib folder
tomcat's lib folder
It's recommended to put it in tomcat's lib, because drivers are singletons and if you have several apps with different versions of the driver in the same container bad things will happen.
How do I go about connecting to this remote db?
Connecting to a remote DB is the same as connecting to alocal DB. Just pass the correct DB address in the connection string.

Related

SQL Azure and Connection Pooling

I have been searching high and low and gathered bits and pieces, apologies if this has already been answered elsewhere but I am unable to find it.
I am writing a web application in Java with Tomcat, and SQL Azure in the backend.
There are multiple servlets accessing the SQL Azure DB. I would like to use Connection Pools as managed by Tomcat 8.5
My application context.xml in META-INF is as follows:
<Context>
<Resource name="jdbc/sqlazure"
auth="Container"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
type="javax.sql.DataSource"
maxIdle="30"
username="[username]"
password="[password]"
url="jdbc:sqlserver://[database]:1433;database=BackInfo;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30"
removeAbandonedTimeout="30"
logAbandoned="true" />
</Context>
In the Java Code, I access the typical way:
InitialContext ic = new InitialContext();ds = (DataSource)ic.lookup("java:comp/env/jdbc/sqlazure");
try(Connection con = ds.getConnection())....
Everything seems to work, so let me confirm my understanding here:
I do not need to specify a separate web.xml since I'm using Tomcat 8.5. Correct ?
Azure will automatically create a pool when I connect in this manner. The number of connections in the pool etc cannot (do not need to?) be configured.
Before I realized I would have other servlets that need to access the database, I had one servlet directly creating a Datasource via SQLServerConnectionPoolDataSource and getting a connection from there. The documentation states:
SQLServerConnectionPoolDataSource is typically used in Java Application Server environments that support built-in connection pooling and require a ConnectionPoolDataSource to provide physical connections, such as Java Platform, Enterprise Edition (Java EE) application servers that provide JDBC 3.0 API spec connection pooling.
Does this mean that when I use SQLServerConnectionPoolDataSource directly to ask for a connection, it will check if Tomcat supports pooling and then is basically using JDBC mechanisms to create a pool of SQL Azure connections managed by Tomcat ?
When getting the DataSource via Tomcat JNDI lookup, using SQLServerDriver as specified in context.xml. When the web app starts up, it will check context.xml and use SQLServerDriver to connect to SQL Azure, check if pooling is supported, if yes then Tomcat is using the driver to automatically creating a connection pool DataSource that it returns ?
I also just thought of one other question. Would it make sense to have a Singleton DataSource class that returns a reference to the pooled connection DataSource, or would it be better to have each servlet lookup the datasource in its init() and store in a private variable ?
Thanks
Based on my understanding, the jdbc connection pool for SQL Server is created by Java Application, not Azure does. My suggestion is that you need to refer to the Tomcat offical documents below to understand the JNDI Resources & JDBC DataSource.
JNDI Resources: http://tomcat.apache.org/tomcat-8.5-doc/jndi-resources-howto.html
JDBC DataSource: http://tomcat.apache.org/tomcat-8.5-doc/jndi-datasource-examples-howto.html

Configuring web application to connect to database

I have java web application using struts 2 and running on JBoss server. We don't use Spring. This application does not use any database right now. They have moved some hard coded data in the application to database and have asked me to start using the database. I'll have to connect to the database to start with.
I have two conditions that have to be met:
I am told we can't reconfigure the server since it is read only (which means I cannot create DataSource on the server[add *-ds.xml to server] - Does it have any other meaning ?) -
(This leaves me with an option to use DriverManager. Is there a better way ?)
. They have told me to keep the database connection properties file out of the ear file and in the config directory. (Does this mean that I have to place the config file somewhere inside the jboss server? What does this mean ? Will this eventually make me to "reconfigure" the server ?)
How do I place the database connection properties file outside the EAR and still have my DAO layer access the configuration properties ?

Building Production Release - DB Connection Credentials

We have a build that can package war files for specific environments where all our property files are embedded in the archive (war file).
We are now about to build for production. My concern is the codebase will need to expose the production database password and although unlikely there is a risk where the production build profile could be run with a negative effect.
Options I thought of to negate this risk is to not store the production details in SVN and:
Have the administrators override system properties which are used to connect to the DB, or
Have the container manage the DB connection instead of c3p0, this way they can manage this configuration themselves.
Do you have any advice?
You should definitely not be putting the production DB username and password into your source control system. Your app should be getting its DB connection (eg a DataSource) using JNDI which is controlled/restricted by the admins on the production environment.
For example, if your app is deployed to Tomcat, you have the following in tomcat/conf/context.xml
<Resource name="jdbc/myDB"
auth="Container"
type="javax.sql.DataSource"
maxActive="20"
maxIdle="10"
maxWait="3000"
username="myusername"
password="mypassword"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://myhost:3306/myschema"
defaultAutoCommit="false"/>
..and the connection is obtained from java:/comp/env/jdbc/myDB without your app ever having to provide a username or password. The tomcat installation is protected on the prod servers by the admins, so it is unavailable to anyone without admin access on your prod server.
In production I favor the approach to not store credentials on property files at all. Instead I prefer the application server to supply the credentials using jndi.
If you are using Apache Tomcat, see for instance their jndi reference.
I have tried both having properties in the archive and outside of the archive, and having them outside of the archive is much easier to manage this kind of problem.
Some things to note:
To the extent that is possible, you can have defaults for properties, so that if the property is not found it will use the default (for example, using "localhost" as the default database connection URL).
You can still keep property files for non-production environments in source control alongside the code.
Using these two policies, developers can be responsible for managing non-production property files, which also therefore serve as examples to the production admin. It also keeps most of the properties centralized in source control, giving some of the benefits of keeping things centralized, while still decoupling the properties enough.
EDIT: Note that JNDI is an option, but architecturally it is the same as storing property files outside - you still need to take care to version these not have them be loose in different environments.

How to configure tomcat 6.0 for mysql

I'm using Tomcat 6.0, and I want to know how can I configure Tomcat's server.xml file to connect to mysql database, and enable form based authentication in java.
I'm currently using mysql 5.1, and I've already downloaded mysql connector jar file, and put in lib directory of Tomcat.
I'm guessing you want Tomcat to create connection pool to MySQL database. In that case, you don't need to configure server.xml file. In the context.xml file you need to add a <Resource> element, something like this:
<Resource name="jdbc/MySQLPool" auth="Container" type="javax.sql.DataSource"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
maxActive="100" maxIdle="30" maxWait="10000"
username="USERNAME" password="PASSWORD"
driverClassName="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource"
url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=Cp1251"
removeAbandoned="true" />
(I'm not sure if that's the correct driverClassName for MySQL, but your Resource should look somewhat like this).
For more info, try checking Tomcat's documentation on JNDI Resources and JDBC DataSources.
Typically context.xml and server.xml are separated, and you usually configure a data source on web-app level, that is in the context of that web app. The reason for that is that a data source connects not so much to a server but to a database within that server, and having multiple apps accessing the same database is not always a good idea (if you didn't design the apps for that).
That said, have a look at this tomcat wiki page which describes what you want (or what I think you want).
For authentication check out this thread on velocity reviews.

Do Tomcat JDBC Connection pools get shared between instances?

We have a web application right now that we deploy a copy for each client. Our current deployment strategy is to create a uniquely named jdbc connection pool for each instance.
so say jdbc/client. They are specified like this...
< Context path="/"
reloadable="true"
docBase="\home\client\ROOT"
debug="5" >
< Resource name="jdbc/client"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
validationQuery="SELECT 1"
testWhileIdle="true"
timeBetweenEvictionRunsMillis="300000"
numTestsPerEvictionRun="6"
minEvictableIdleTimeMillis="1800000"
maxWait="10000"
username="user"
password="pass"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://databaseserver:3306/client ?zeroDateTimeBehavior=convertToNull&jdbcCompliantTruncation=false"/>
< /Context>
The question is, if I were to standardize it so that instead of unique names the connection pool is called jdbc/database on all deployed instances, is there a chance of database crossing, ie one customer in another customer's database, or are these localized to a specific deployed instance?
Thoughts?
Thanks,
Scott
No. The scope of the data source name is one Tomcat instance.
If you are starting a separate Tomcat process for each customer, all that matters is how the data source is configured, not what Tomcat calls it. As long as each data source is configured to use a different database, there won't be any cross talk.
This depends on how you deploy application for each client,
If each client gets their own Tomcat installation (they have different CATALINA_HOME), there is no chance for it to cross.
If they all use the same installation but run as different host in Tomcat, you need to make sure you don't define the datasource in conf/context.xml, which is shared by all hosts.
If all clients share the same Tomcat instances and they are simply different web apps, more attention is required. You need to define the datasource either in META-INF/context.xml or WEB-INF/web.xml. For further isolation, you should copy dbcp.jar to WEB-INF/lib of each application so they use their own DBCP instance.
If you're defining the JNDI DataSource resource within the Context for a deployment of the application, I believe you could even have multiple copies of the same application running in the same Tomcat instance and using the same JNDI name to access different databases. If each application instance is running in a different instance of Tomcat completely, there is certainly no way that one instance would be referring to the database specified for another instance.
No there is no chance of database crossing becoz the scope of the data source name is one Tomcat instance and you can have multiple data source in single tomcat instance .... so as long as data source is different there is no chance of database crossing.....

Categories