I'm from a UFT background. With that being said I don't know much about JAVA. I have the following code where I connect to sql server and retrieve some values and loop through them and then print them out to log. There is a string array varialbe "String[] sqlArr" that holds all the values retrieved from sql server. How to return that "String[] sqlArr" variable to a different class? In this case to main class.
I'm not exactly sure how to return the array but I have tried changing the return type to String and place a return statement right before method close curly brace. I get a compilation error.
What I want to know is how can I, 1. Instead of looping it inside the method, return the array to Main so i can use each value of the array to my need. 2. What should be the return type if not void in this case? 3. Maybe someone can recommend me or modify my script in a different way which will look more professional.
Any suggestions comments on that will be highly appreciated.
package com.mmia;
import java.sql.*;
public class Connect2SQLServer {
//Current Username
private String currentUser = System.getProperty("user.name");
public void connect2SQLServer() throws SQLException, ClassNotFoundException {
//Loading the required JDBC Driver class
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Creating a connection to the database
Connection conn = DriverManager.getConnection("jdbc:sqlserver://XXXXXXXXXXX;databaseName=Data_Table_Name;integratedSecurity=true");
//Executing SQL query and fetching the result
Statement st = conn.createStatement();
//Sql query
String sqlStr = "Select * From PropertiesTable where Username =" + "'" + currentUser + "'";
//Execute the query
ResultSet rs = st.executeQuery(sqlStr);
while (rs.next()) {
String Username = rs.getString("Username");
String Environment = rs.getString("Environment");
String WebDealer = rs.getString("WebDealer");
String WebAgent = rs.getString("WebAgent");
String WebPassword = rs.getString("WebPassword");
String InternalUser = rs.getString("InternalUser");
String InternalPassword = rs.getString("InternalPassword");
String Browser = rs.getString("Browser");
//String[] sqlArr;
String[] sqlArr = {Username, Environment, WebDealer, WebAgent, WebPassword, InternalUser, InternalPassword, Browser};
for (int i = 0; i < sqlArr.length; i++) {
System.out.println(sqlArr[i]);
}
}
}
}
return sqlArr;in the last line of the method (you'll have to change the method signature fromvoidtoString[]as well).*. That way you don't lose performance if more columns get added to the table in the database later on, or if you need to join other tables in your query. 2) Your code is vulnerable to SQL injections. If the user name was' or '1' = '1, it would select all rows in that table. Use prepared statements instead: docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html