How to connect to Mysql in Selenium script?
Step 1: Import Mysql connector (JDBC driver):
Download connector from:
Download this jar file and import in Eclipse : MySQL-connector-java-5.1.18-bin.jar
Follow these steps in Eclipse:
Add the downloaded Jar to your Project:
1. Right-click on your Java File. Then click on Build Path -> Configure build path.
2. Select libraries.
3. Click on add external JARs.
4. You will see MySQL connector java in your library.
5. Click on open to add it to the project.
Step 2: Script for creating connection:
public void dbConnection( ) throws Exception { //connection url String dbUrl= "jdbc:mysql://localhost/Accord_new"; String dbUsername= "dbusername"; String dbPassword= "dbpwd"; // load Mysql jdbc driver Class.forName("com.mysql.jdbc.Driver"); //Get connection to DB Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword); //create statement object Statement stmt = con.createStatement(); //test query String query= "select * from users where name not null"; //send sql query to database ResultSet rs= stmt.executeQuery(query); // while loop to iterate ResultSet to get all rows while (rs.next()) { String name =rs.getString("name"); String email =rs.getString("email_id"); int id = rs.getInt("id"); System.out.println(name); System.out.println(email); System.out.println(id); } //Close db connection con.close(); }