My Blog List

Saturday, March 17, 2012

Java - DataBase Connections

For those who are working in selenium and related automation tools using Java API are in need of connecting back end databases to verify the values. Here is the high level info.
Required package:
  1. import java.sql.*;
Code Sample:
  1. //Initializing the driver for JDBC connection
  2. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  3. //Creating properties to be passed for connection
  4. Properties properties = new Properties();
  5. properties.put("user", "shan");
  6. properties.put("password", "pass");
  7. properties.put("characterEncoding", "ISO-8859-1");
  8. properties.put("useUnicode", "true");
  9. //actual connection string
  10. String url = "jdbc:mysql://ServerName:port/DataBaseName";
  11. //Getting the connection object using properties and url
  12. Connection conn = DriverManager.getConnection(url, properties);
  13. //Creating a statement of type CreateStatement
  14. Statement stmt = conn.createStatement(); //for Insert/Update, create of type conn.executeUpdate
  15. String sql = "select * from [Sheet1$]";
  16. RecordSet rs = stmt.executeQuery(sql);
  17. while({
  18.    username = rs.getString("username");
  19.    password = rs.getString("Password");
  20. }
Here are the driver and Connection String for different DBs.
Driver: Class.forName("com.mysql.jdbc.Driver").newInstance();
URL   : jdbc:mysql://serverName:port/DBName
Driver: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
URL   : jdbc:derby:pathToDB:DBName;create=true;
Driver: Class.forName("");
URL   : jdbc:microsoft:sqlserver://serverName:port/DBName


1 comment:

  1. Thanks for sharing great information in your blog. Got to learn new things from your Blog . It was very nice blog to learn about Selenium