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(rs.next()){
  18.    username = rs.getString("username");
  19.    password = rs.getString("Password");
  20. }
Here are the driver and Connection String for different DBs.
MySQL:
Driver: Class.forName("com.mysql.jdbc.Driver").newInstance();
URL   : jdbc:mysql://serverName:port/DBName
Derby:
Driver: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
URL   : jdbc:derby:pathToDB:DBName;create=true;
SQL:
Driver: Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
URL   : jdbc:microsoft:sqlserver://serverName:port/DBName


Refer http://www.linglom.com/2007/03/04/accessing-sql-server-on-netbeans-using-jdbc-part-i-create-a-connection/

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

    ReplyDelete