简体   繁体   中英

Call database oracle connection from a method to another in Java

I need to call some strings like (username) from the below method. the package name is login and the database method is SQLConnector and the testcase is Firstlogin. I need to call the connection of database in Firstlogin to use strings from it in Firstlogin and to execute queries in Firstlogin too:

package login;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLConnector {
static Connection con = null;
private static Statement stmt;
public static String DB_URL =  "jdbc:oracle:thin:@10.96.0.65:1521:orcl";   
public static String DB_USER = "POS_SOF";
public static String DB_PASSWORD = "POS_SOF";
    static String username;

@Before
public void setUp() throws Exception {
       try{
              String dbClass = "oracle.jdbc.driver.OracleDriver";
              Class.forName(dbClass).newInstance();
              Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
              stmt = con.createStatement();
              }
              catch (Exception e)
              {
                    e.printStackTrace();
              }

}
@Test
public void test() {
       try{
       String query = "select * from users where id = '45450'";

       String expectedEmpName = "test1234";
       ResultSet res = stmt.executeQuery(query);
    while (res.next())
       {
        username = res.getString("user_name");
        System.out.print(username);
        assertEquals(expectedEmpName, username);

       }

       }

       catch(Exception e)

       {

              e.printStackTrace();

       }     

}
@After
public void tearDown() throws Exception {
       if (con != null) {
       con.close();

       }

}

} in the second method which I need to use the database connection in:

package login;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import login.SQLConnector;


public class FirstLogin {

private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();

@Before
public void setUp() throws Exception {
    System.setProperty("webdriver.chrome.driver", "D://DownLoads/chromedriver_win32/chromedriver.exe");
    driver = new ChromeDriver();
    baseUrl = "https://100.96.0.650:9443";
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}

@Test
public void testAddAccount() throws Exception {
    driver.get(baseUrl + "/POSAdminTool/AdminTool/SearchPOS.faces");
    driver.manage().window().maximize();
    driver.findElement(By.id("form1:usernameLabel")).clear();
    driver.findElement(By.id("form1:usernameLabel")).sendKeys(SQLConnector.username);
    driver.findElement(By.id("form1:passwordLabel")).clear();
    driver.findElement(By.id("form1:passwordLabel")).sendKeys("1234");
    driver.findElement(By.id("form1:btn_login")).click();
    Thread.sleep(1000);
    Actions action = new Actions(driver);
    WebElement element = driver.findElement(By.cssSelector("html body table.mainTable tbody tr td p.menuItem a"));
    action.moveToElement(element);
    action.click();
    action.perform();
    driver.findElement(By.linkText("Add Account")).click();
    driver.findElement(By.id("addPOS:locationID")).clear();
    driver.findElement(By.id("addPOS:locationID")).sendKeys("9999");
    driver.findElement(By.id("addPOS:menu1")).clear();
    driver.findElement(By.id("addPOS:menu1")).sendKeys("10000");
    driver.findElement(By.id("addPOS:menuStatus1")).click();
    new Select(driver.findElement(By.id("addPOS:usageList"))).selectByVisibleText("Pharmacy");
    driver.findElement(By.id("addPOS:textareaDescription1")).clear();
    driver.findElement(By.id("addPOS:textareaDescription1")).sendKeys("New");
    driver.findElement(By.id("addPOS:addAcctTerminal")).click();
    new Select(driver.findElement(By.id("AddAcctTerminalData:statusList"))).selectByVisibleText("Active");
    new Select(driver.findElement(By.id("AddAcctTerminalData:TermList"))).selectByVisibleText("Point of Sale");
    driver.findElement(By.id("AddAcctTerminalData:textSN1")).clear();
    driver.findElement(By.id("AddAcctTerminalData:textSN1")).sendKeys("22-55-88");
    driver.findElement(By.id("AddAcctTerminalData:textPin1")).clear();
    driver.findElement(By.id("AddAcctTerminalData:textPin1")).sendKeys("1234");
    driver.findElement(By.id("AddAcctTerminalData:add")).click();
    driver.findElement(By.id("addPOS:textDailyLimit1")).clear();
    driver.findElement(By.id("addPOS:textDailyLimit1")).sendKeys("10000");
    driver.findElement(By.id("addPOS:textCreditLimit1")).clear();
    driver.findElement(By.id("addPOS:textCreditLimit1")).sendKeys("10000");
    driver.findElement(By.id("addPOS:button1")).click();
    assertEquals("Account Added Successfully", driver.findElement(By.id("AddAccountSuccess:CorrectMessage")).getText());
    String AddedAccount = "SELECT CODE FROM ACCOUNTS WEHER ID IN (SELECT MAX(ID) FROM ACCOUNTS)";
    String AccountCode = driver.findElement(By.id("AddAccountSuccess:AccountCode")).getText();
    System.out.print(AccountCode);
    System.out.print(AddedAccount);
    assertEquals(AddedAccount, AccountCode);

}

@After
public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
        fail(verificationErrorString);
    }
}

}

You need to make two changes:

  • Make Connection object non static
  • Remove the declaration of local variable con in @Before method, ie change

    Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);

    to

    con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);

Declaring a local variable in method (with the same name as instance variable) shadows the instance variable and hence, the instance variable never gets initialised. With the above change, con will get initialised before any test runs and you will be able to use it in any method.

try this:

import java.sql.SQLException;

import oracle.jdbc.OraclePreparedStatement;

    public class SQLConnector {
    static final String DB_URL =  "jdbc:oracle:thin:@10.96.0.65:1521:orcl";   
    static final String DB_USER = "POS_SOF";
    static final String DB_PASSWORD = "POS_SOF";
        static String username;

    @Before
    public Connection setUp() throws Exception {
    Connection connection = null;

           try {
                try {

                    Class.forName(JDBC_DRIVER);

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    return;
                }

                System.out.println("Oracle JDBC Driver Registered!");

                  System.out.println("Status: \n - Connecting to database...");
                  connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
                  System.out.println(" - You are connected to the " + DB_URL);
                  }
                  catch (Exception e)
                  {
                        e.printStackTrace();
                  }
        return connection;
    }

    @Test
    public void test() {
        Connection conn = setUp();
           try {
                /*Oracle thin connection require OraclePreparedStatement class*/
                String query = "select * from users where id = '45450'";
                OraclePreparedStatement stmt = (OraclePreparedStatement) conn.prepareStatement(query); // is not necessary needed to pass query variable

                String expectedEmpName = "test1234";
                ResultSet res = stmt.executeQuery(query);
                while (res.next()) {
                    username = res.getString("user_name");
                    System.out.print(username);
                    assertEquals(expectedEmpName, username);
               }

           } 
           catch (SQLException se) {
                se.printStackTrace();
            } 
            catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null)
                        conn.close();
                } catch (SQLException se) {
                    se.printStackTrace();
                }
            }   
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM