I want simple test for JDBC connection, I don't use framework, only JDBC and JUnit. Can I perform this test with JUnit? I have no idea how to even test loading driver, please give me some example of connection test.
Connection client:
package newpackage.db;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SqlConnection {
private Connection con;
private String name;
private String url;
private String password;
private String driver;
public SqlConnection() {
this.name = "root";
this.password = "12345";
this.url = "";
this.driver = "com.mysql.jdbc.Driver";
}
public Connection getConnection() {
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SqlConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
Test case:
public void testDriverManager() {
SqlConnection conClient = new SqlConnection();
assertEquals(conClient.getConnection(),...);
or
assertTrue(conClient.getConnection(),...);
}
Basically, you can follow this guide for the drivermanager in order to establish a connection.
http://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html
The best test for a connection is reading some basic stuff from your database. E.g. select 1 from dual
Be aware that this test requires a running database! Keep the amount of these integrative tests low, as they do not scale well and require a certain environment given. It makes continuous integration on e.g. Hudson kind of more difficult, as you will have to install a database on all continuous integration server nodes and keep it running.
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
am getting an exception as java.sql.Connection.prepareStatement(String) because con is null, I don't know why as I have already added MySQL Connector jar file.
import java.sql.Connection;
import java.sql.PreparedStatement;
public class Studentdao {
public static boolean insertStudenttoDB(Student st) {
boolean f=false;
try {
Connection con =CP.createc();
//jdbc code
String q="insert into students(sname,sphone scity)values(?,?,?)";
PreparedStatement pstmt=con.prepareStatement(q);
pstmt.setString(1,st.getStudentname());
pstmt.setString(2,st.getStudentcity());
pstmt.setLong(3,st.getStudentphone());
//execute
pstmt.executeUpdate();
f=true;
}
catch(Exception e) {
e.printStackTrace();
}
return f;
}
}
This is my connection program
import java.sql.Connection;
import java.sql.DriverManager;
public class CP {
static Connection con;
//load driver
public static Connection createc() {
try {
Class.forName("com.sql.jdbc.Driver");
//creating connection
String user="mysql";
String password="mysql";
String url="jdbc:mysql://localhost:3306/student_manage";
con=DriverManager.getConnection(url,user,password);
}catch(Exception e) {
e.printStackTrace();
}
return con;
}
}
Incorrect class name
You appear to have an incorrect class name, if you are using the Connector/J product as your JDBC driver.
Section 3.6.1 of the Connector/J manual shows the use of "com.mysql.cj.jdbc.Driver" versus your use of "com.sql.jdbc.Driver". Here is their code example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.cj.jdbc.*
// or you will have problems!
public class LoadDriver {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
}
}
DataSource
Note that your use of Class.forName is generally not needed in modern Java. The JDBC architecture was years ago revamped so that now drivers are automatically located and loaded using the Java Service Provider Interface (SPI) technology.
I do suggest you make a habit of using a DataSource to obtain connections rather than calling on the DriverManager. Using DataSource makes your code much more flexible. You will be able to switch JDBC drivers, add connection pooling, and externalize configuration info (server address, database name, user name, password, etc.) for deployment.
Usually your JDBC driver comes with a basic implementation of DataSource. Check the documentation for all the various options you can set, specific to your database (MySQL in this case).
For MySQL, I understand the implementation of DataSource currently provided in Connector/J is com.mysql.cj.jdbc.MysqlDataSource. Caveat: I make regular use of Postgres & H2, not MySQL, so I may not be up-to-date.
See my Answer to another Question for source code of a full example of connecting and working with MySQL. Here are the parts relating to DataSource and Connection.
private DataSource configureDataSource ( )
{
System.out.println( "INFO - `configureDataSource` method. " + Instant.now() );
com.mysql.cj.jdbc.MysqlDataSource dataSource = Objects.requireNonNull( new com.mysql.cj.jdbc.MysqlDataSource() ); // Implementation of `DataSource` bundled with H2.
dataSource.setServerName( "db-mysql-sfo3-422-do-user-8982-1.x.db.ondigitalocean.com" );
dataSource.setPortNumber( 24_090 );
dataSource.setDatabaseName( "defaultdb" );
dataSource.setUser( "scott" );
dataSource.setPassword( "tiger" );
return dataSource;
}
Early in the lifecycle of your app, instantiate and retain the DataSource object returned from that method. Remember, a DataSource holds only the configuration details; it is not an open resource itself, and need not be closed.
DataSource dataSource = this.configureDataSource();
To open a connection, pass the DataSource to your method that wants to connect to the database.
private void dumpTable ( DataSource dataSource ) { … }
Here is a piece of that dumpTable method.
Notice the use of try-with-resources syntax to automatically close the open resources in the order in which they were declared, even in case of failure with exceptions being thrown.
String sql = "SELECT * FROM event_ ;";
try (
Connection conn = dataSource.getConnection() ; // 🡄 Use the passed `DataSource` object to ask for a `Connection` object.
Statement stmt = conn.createStatement() ;
ResultSet rs = stmt.executeQuery( sql ) ;
)
{
…
}
catch ( SQLException e )
{
e.printStackTrace();
}
here's the code I tried to connect java class with mysql. Make sure you have to add the required driver to your libraries.
import java.sql.Connection;
import java.sql.DriverManager;
public class Server {
public static Connection getConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String urls = "127.0.0.1";//you can even replace this with localhost
String username = "yourusername";
String password = "1234";
Connection conn = DriverManager.getConnection("jdbc:mysql://"+urls+":3306/yourdb?useUnicode=yes&characterEncoding=UTF-8", username, password);
return conn;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
I am having an issue with an app I am testing. I am using Android Studio and JTDS 1.3.1. I am just trying to test connecting to the database. The end product will be a label application only used within our company on our network. I have tried Microsoft's JDBC driver as well, with no success. The app crashes when it tries to create a connection. I have added JTDS as a module and a dependency. The app is just a button that calls a static method and a text view to display an error or success if it works. If I don't load the database driver I do get a SqlException error for no suitable driver found. When I do load the driver the app closes with no error reported.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBHelper {
public static String checkConnection() {
String message;
String username = "username";
String password = "password";
String connectionURL = "jdbc:jtds:sqlserver://server-name/database-name";
try (Connection connection = DriverManager.getConnection(connectionURL, username, password)) {
message = "Success";
return message;
} catch (SQLException sqle) {
message = sqle.getMessage();
return message;
}
}
}
I know it is too late but try using jtds 1.2.7 version jar
i guess this is a newbie question...Don't seem to find it anywhere, so i thought i asked, hope you don't get mad :) I am really new to all this jsp and java thing and try to figure out what's going on.
So, I have created 2 classes that create the connection to my postgres database. The thought was to have a class that creates the connection and use it anytime i need it, cause i will need to retrieve data many times in the future.
The first one: DbContract.java
package Database;
public class DbContract
{
public static final String HOST = "jdbc:postgresql://localhost:5432/";
public static final String DB_NAME = "DB_1";
public static final String USERNAME = "postgres";
public static final String PASSWORD = "12345";
}
and the second one: TestConnection.java
package Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestConnection
{
public static void main(String[] args)
{
try
{
Class.forName("org.postgresql.Driver");
Connection c;
c = DriverManager.getConnection(
DbContract.HOST+DbContract.DB_NAME,
DbContract.USERNAME,
DbContract.PASSWORD);
System.out.println("DB connected");
}
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
}
}
Now, i want to use these, in order to retrieve data from a existing database i have (postgres and it is filled with records.), BUT from a jsp page. Is it possible?
Can anyone, help me step by step to do it, or is it too easy?
thanks in advance
So I know that this may have come up a few times, but this is actually a little different. I want to authenticate a login from the authentication server. This is my code:
import java.sql.*;
public class TestConnect {
public static void main(String args[]) {
String host = "https://authserver.mojang.com";
String user = "--username--";
String pass = "--password--";
try {
Connection con = DriverManager.getConnection(host, user, pass);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
So the error im getting everytime is the following:
No driver found for https://authserver.mojang.com
A little help would be welcome :)
Read the getConnection method's doc:
http://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String,%20java.util.Properties)
url - a database url of the form jdbc:subprotocol:subname
Your url is not valid.
I have created the web service and in that i am coonecting the database and access the information form that but couldn't successful.
/
**
*
*/
package com.xxxxx.www.testprocess;
import javax.jws.*;
import java.sql.*;
import java.util.*;
/**
* #author Suryasol6
*
*/
#WebService(name="TestProcess",targetNamespace ="http://www.example.org/TestProcess")
public class TestProcess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
private static final String CONNECTION_URL = "jdbc:mysql://localhost:3306/java_test?user=root&;password=";
#WebMethod(action="http://www.example.org/TestProcess/TestLogin")
#WebResult(name="TestLoginresponse")
public String TestLogin(#WebParam(name="name")
String name,#WebParam(name="password")
String password)
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception e)
{
return "fail here";
}
return "pass";
}
}
I can publish the web service but when i try to connect the web service with parametes, it fails to load the jdbc driver.
But when i try to run this file as seperate this worked.
Can anybody help me??
Do you have the MySQL driver jar in the JBoss server lib directory? It should go in:
<JBoss_home>/server/default/lib
When you run it manually you may be specifying the classpath to include the jar, but JBoss needs it there.