Update on Database Connection with MySQL | Selenium Forum
S
Sarthak Kumar Panda Posted on 23/07/2019

Hi Everyone,

Please note that there has been a minute change wrt to how jdbc is interacting with MySQL. 

Please download this jar file -> mysql-connector-java-8.0.17

And there is a small change in the Driver.class where in we used to write

Before:

String driver = "com.mysql.jdbc.Driver";

Now:

String driver = "com.mysql.cj.jdbc.Driver";

 

Also I am attaching the code which I have written. Of course all the help came from Ashish Sir but this is an update. Code is working fine and you can check. Just make sure that you make your own database and your table and add the values inside it. 

I made a Java Project. Made a package databaseConnection and made a Class TestNGDataBase. Did not select Main Method as I am using TestNG

 

package databaseConnection;
import java.sql.*;
import org.testng.annotations.*;

public class TestNGDataBase {
String url = "jdbc:mysql://localhost:3306/";
String driver = "com.mysql.cj.jdbc.Driver";
String dbName = "selenium";
String username = "root";
String password = "root" ;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Statement stmt = null;
CallableStatement cstmt = null;

@BeforeTest // connection with Database
public void connectwithDB() throws Exception{
Class.forName(driver).newInstance();
System.out.println("Driver Loaded");
conn = DriverManager.getConnection(url+dbName,username,password );
System.out.println(conn.isClosed());
}

@Test
public void workwithDB() throws Exception {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM EMPLOYEE");

while( rs.next()) {
System.out.println(rs.getString(1) + "-------" + rs.getString(2)+ "------" + rs.getString(3));
}

System.out.println("-----------------------------------------------------------------------------------");

pstmt = conn.prepareStatement("SELECT * FROM EMPLOYEE WHERE PLACE = ? and AGE = ?");
pstmt.setString(1, "LONDON");
pstmt.setInt(2, 30);
rs = pstmt.executeQuery();

while( rs.next()) {
System.out.println(rs.getString(1) + "-------" + rs.getString(2)+ "------" + rs.getString(3));
}
/*****************************Stored Procedures********************************************/

/*cstmt = conn.prepareCall("{Call getTestData(?, ?, ?, ?)}");
cstmt.registerOutParameter(1, java.sql.Types.DECIMAL);
cstmt.setString(2, "TestName");
cstmt.setString(3, "TestName1");
cstmt.setString(4, "TestName2");
cstmt.executeUpdate();
double d = cstmt.getDouble(1); */

}
@AfterTest
public void disconnect() {
try {
if(rs!=null)
rs.close();
if(pstmt!=null)
pstmt.close();
if(conn!= null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}



A
Ashish Thakur Replied on 24/07/2019

Thanks for the information