Ambiguous behavior of ResultSet - java

I have a requirement to create separate POJO which will set/get sql ResultSet and use its methods throughout my project code like below. I have created below 2 classes
public class Tester3
{
public MyResultSet test() throws SQLException{
MyResultSet mrs = new MyResultSet();
PreparedStatement ps = null;
String values = null;
boolean flag = false;
String one = "'12'";
String two = "'jt'";
String a = null;
String b = null;
try {
if(flag==true)
{
values = "'3%'";
a =null;
b = "OR id IN(\'" +a+ "\')";
}else
{
values = "'%'";
a = one + "," + two;
b = "AND id IN("+a+")";
}
String sql = "SELECT * FROM veracodetable where orts like PARAM RAMAN";
sql = sql.replaceFirst("PARAM", values);
sql = sql.replaceFirst("RAMAN", b);
System.out.println("SQL: "+sql);
ps = new Connection1().getConnection().prepareStatement(sql);
ps.executeQuery();
mrs.setRs(ps.executeQuery());
System.out.println("ResultSet: "+mrs.getRs().next());
} catch (SQLException e) {
e.printStackTrace();
}
return mrs;
}
public static void main(String[] args) throws SQLException {
Tester3 t = new Tester3();
MyResultSet rs = t.test();
System.out.println("ResultSet: "+rs.getRs().next());
}
}
public class MyResultSet {
ResultSet rs = null;
public ResultSet getRs() {
return rs;
}
public void setRs(ResultSet rs) {
this.rs = rs;
}
}
When executed above code with separate POJO MyResultSet, I don't get any result in ResultSet. However if I skip POJO implementation and use resultSet directly, I am able to get results.
Is rs.getRs() invoking at all? If not, why?

I would separate the statements as they dont't perform the same function, and then populate;
PreparedStatemet ps = null;
ResultSet rs = null;
if(flag){
String stmt = "...?...?";
ps = con.preparedStatement(stmt);
ps.setString(0,a);
ps.setString(1,b);
rs = ps.executeQuery;
}else{
String stmt = "...?...?";
ps = con.preparedStatement(stmt);
ps.setString(0,a);
ps.setString(1,b);
rs = ps.executeQuery;
}
}

Related

statement.executeQuery) not working in NetBeans java

I am trying to output the first column (nameID) of my table (StudentInfo) in my database. But the statement.executeQuery is not working and ResultSet.next() is false.
Java NetBeans program
Calls sqlite database
Uses "jdbc:sqlite:ProjectWeekDB.sqlite" as url
private static Connection connection = null;
private static PreparedStatement stmt = null;
private static Statement statement = null;
private static ResultSet results = null;
public static void createNewDatabase() {
String sqlData = "SELECT * FROM StudentInfo";
String url;
try {
connection = DriverManager.getConnection(url);
if (connection != null) {
statement = connection.createStatement();
stmt = connection.prepareStatement(sqlData);
statement.executeUpdate(sqlData);
results = statement.executeQuery(sqlData);
while (results.next()) {
print(results.getInt("nameID"));
}
stmt.close();
results.close();
}
} catch (SQLException e) {
print(e.getMessage());
}
}
public static void main(String[] args) {
createNewDatabase();
}
It just prints out BUILD successful without actually displaying the first column in the database.

No suitable driver found for jdbc:mysql//localhost/sakila

I'm trying to set up JDBC but I'm getting this error.
I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.
public class FilmLength {
public static void main(String[] args) throws SQLException {
Connection dbCon = null;
PreparedStatement st = null;
ResultSet rs = null;
String url = "jdbc:mysql//localhost:3306/sakila";
String username = "devuser";
String password = "Demo#123";
String query = "select * from film ";
try {
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(url,username,password);
st = dbCon.prepareStatement(query);
rs = st.executeQuery();
while(rs.next()) {
String title = rs.getString(1);
System.out.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
dbCon.close();
st.close();
rs.close();
}
}
}
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";
it should be
String url = "jdbc:mysql://localhost:3306/sakila";

How to use a variable value declared in servlet into a new Java class?

I have a login servlet where I have a login query in my post method from the query I am getting username, password, company name and ID
I am storing all this values in a variable like
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String companyDB,nameDB,idDB;
try {
con = DBConnection.createConnection();
statement = con.createStatement();
String sql = " SELECT MT_USERS.MT_USERS_VCLOGINCODE AS USERID, MT_USERS.MT_USERS_VCUSERPASSWORD AS PASSWORDID, MT_USERS.MT_USERS_VCUSERNAME AS NAME, (SELECT MT_DISTRIBUTR_VCDISTRIBUTRNAME FROM MT_DISTRIBUTR WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS COMPANYNAME ,(SELECT mt_distributr_vcdistributrcode FROM mt_distributr WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS ID FROM MT_USERS WHERE MT_USERS_VCLOGINCODE='admin' AND MT_USERS_VCUSERPASSWORD ='admin'";
resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
companyDB = resultSet.getString("COMPANYNAME");
nameDB = resultSet.getString("name");
idDB = resultset.getString("ID");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Now I have an another class where I am writing a query and in that query I want to use idDB like
My new class is
public class Outlet {
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
public List<String> getoutlet() throws ClassNotFoundException, SQLException {
List<String> list = new ArrayList<String>();
con = DBConnection.createConnection();
statement = con.createStatement();
try {
ResultSet resultSet = statement.executeQuery("select * from ecustomer where CUSTOMERIDENTIFIER in(select CUSTOMERIDENTIFIER from mt_distributrol where mt_distributr_vcdistributrcode = 'AAAA'");
while (resultSet.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
Where mt_distributr_vcdistributrcode = 'AAAA'" at the place of 'AAAA' I have to pass a variable which has the value of idDB
You may use a prepared statement here:
String sql = "SELECT CUSTOMERDESCRIPTOR FROM ecustomer WHERE CUSTOMERIDENTIFIER IN (";
sql += "SELECT CUSTOMERIDENTIFIER FROM mt_distributrol ";
sql += "WHERE mt_distributr_vcdistributrcode = ?)");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "AAAA");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
I actually find that MkYong does a good job of explaining prepared statements in Java, see here, but any good documentation is a good place to start looking. And see Oracle Tutorial.

getting null in mock object

I am trying to mock a object in the junit test file. I am getting value in test file
public void TestMethod() throws SQLException{
String projectID = "Test";
Connection connectionMock = Mockito.mock(Connection.class);
PreparedStatement preparedStatementMock = Mockito.mock(PreparedStatement.class);
ResultSet resultSetMock = Mockito.mock(ResultSet.class);
mockStatic(Manager.class);
Worker workerMock = Mockito.mock(Worker.class);
mockingDetails(workerMock);
mock(PreparedStatement.class);
mock(ResultSet.class);
when(workerMock.getProjectId())
.thenReturn(projectID);
when(Manager.getDatabaseConnection())
.thenReturn(connectionMock);
when(connectionMock.prepareStatement(""))
.thenReturn(preparedStatementMock);
when(preparedStatementMock.executeQuery())
.thenReturn(resultSetMock);
//mockStatic(Manager.class);
System.out.println("workerMock--------->"+workerMock);
System.out.println("prepared stmt--------->"+preparedStatementMock);
assertNotNull(service.getProtocol());
}
If I print here I am getting value worker and prepared statement like this value
"Mock for Worker, hashCode: 853323835"
If I print same in my real method, I am getting null for both worker and prepared statement. I have used annotations
#RunWith(PowerMockRunner.class)
#PrepareForTest(Manager.class)
in the test class
public String Method() throws SQLException
{
Connection conn = Manager.getDatabaseConnection();
String protocol = null;
StringBuilder qryBuilder = new StringBuilder("MyQuery");
qryBuilder.append("condition = ?");
System.out.println("worker.getProjectId()------------->"+worker);
System.out.println("connection------------->"+conn);
PreparedStatement pst = conn.prepareStatement(qryBuilder.toString());
System.out.println("pst------------->"+pst);
pst.setString(1, worker.getProjectId());
try {
ResultSet rset = pst.executeQuery();
try {
while (rset.next()) {
protocol = rset.getString(1);
}
rset.close();
} finally {
pst.close();
}
} catch (SQLException e) {
throw e;
}
return protocol;
}

Getting null value from table

i have a piece of jsp code . this code takes data from a table and displays it on a console
For integer values it is working good but for String values it displays null
the issue is not with the table . i have tried other tables also but same result
jsp code :
<%
int mots_id = 0 ;
String mots_name = "" ;
String accesstype = "" ;
GetAccess obj = new GetAccess();
List<GetAccessVO> accesslist = obj.access(attUID);
if(accesslist!=null)
{
Iterator<GetAccessVO> iter = accesslist.iterator();
while(iter.hasNext())
{
GetAccessVO getaccessVO = iter.next();
mots_id = getaccessVO.getmotsid();
String mots_name = getaccessVO.getmotsname();
String accesstype = getaccessVO.getaccess();
out.println(accesstype); // it displays null
}
}
%>
java code :
public class GetAccess{
final static DBConnection db=new DBConnection();
public List<GetAccessVO> access(String attuid)
{
List<GetAccessVO> accesslist = new ArrayList<GetAccessVO>();
try
{
Connection con = db.getConnection();
String query ="select mots_id ,mots_name,access_type from ENV_TEAM where userid = ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, attuid);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
GetAccessVO getaccessVO = new GetAccessVO();
getaccessVO.setmotsid(rs.getInt(1));
getaccessVO.setmotsname(rs.getString(2));
getaccessVO.setaccess(rs.getString(3));
accesslist.add(getaccessVO);
}
rs.close();
pstmt.close();
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return accesslist;
}
}
the setter getter class :
public class GetAccessVO {
private int mots_id;
private String mots_name;
private String access;
public String getmotsname() {
return mots_name;
}
public void setmotsname(String mots_name) {
this.mots_name = mots_name;
}
public int getmotsid() {
return mots_id;
}
public void setmotsid(int mots_id) {
this.mots_id = mots_id;
}
public String getaccess() {
return access;
}
public void setaccess(String access) {
this.access = access;
}
}
i have tried almost everything but the String values always are null
SQL> select * from env_team ;
USERID MOTS_ID MOTS_NAME ACCESS_TYPE
------- ---------- ------------------------------ ------------------------------
as045e 7921 BDS external

Categories