繁体   English   中英

在Java中从方法到另一方法调用数据库oracle连接

[英]Call database oracle connection from a method to another in Java

我需要从以下方法中调用一些字符串,例如(username)。 程序包名称为login,数据库方法为SQLConnector,测试用例为Firstlogin。 我需要在Firstlogin中调用数据库连接以在Firstlogin中使用它的字符串并在Firstlogin中执行查询:

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();

       }

}

在第二种方法中,我需要在以下方法中使用数据库连接:

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);
    }
}

}

您需要进行两项更改:

  • Connection对象设为非静态
  • 删除@Before方法中局部变量con的声明,即更改

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

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

在方法中声明局部变量(与实例变量同名)会遮盖实例变量,因此,实例变量永远不会初始化。 通过上述更改, con将在任何测试运行之前被初始化,并且您将能够以任何方法使用它。

尝试这个:

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();
                }
            }   
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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