PreparedStatement pstmt = null;
ResultSet rs = null;
List<SelectItemsDTO> listItem = new ArrayList<SelectItemsDTO>();
try {
StringBuilder query =new StringBuilder();
query = query.append(SLCMQueryConstant.GET_CollegeChid_LIST);
pstmt = conn.prepareStatement(query.toString());
pstmt.setInt(1,commonDto.getOrgID());
rs = pstmt.executeQuery();
int pid= 0;
while (rs.next()) {
pid= rs.getInt("organization_parent_id");
}
if(pid!= 0)
{
query = query.append(SLCMQueryConstant.GET_CollegeSub_LIST.toString());
pstmt = conn.prepareStatement(query.toString());
}
else
{
query = query.append(SLCMQueryConstant.GET_College_LIST.toString());
pstmt = conn.prepareStatement(query.toString());
}
pstmt.setInt(1,commonDto.getOrgID());
rs = pstmt.executeQuery();
while (rs.next()) {
SelectItemsDTO itemTo = new SelectItemsDTO();
itemTo.setItemCode(rs.getString("Organization_Name"));
itemTo.setItemIds(rs.getInt("Organization_ID"));
listItem.add(itemTo);
}
}
public static final String GET_College_LIST= " SELECT Organization_Name,Organization_ID FROM m_organization_master WHERE organization_parent_id = ? ";
public static final String GET_CollegeSub_LIST = " SELECT Organization_Name,Organization_ID FROM m_organization_master WHERE Organization_ID = ? ";
I want to execute query according to if condition .I am getting PID value from database and then used as if condition .This code seems an error no value specified for parameter 1 I have already initialized parameter for passing the values.
Related
I'am trying to update table from multiple columns names(lo1,lo2,...) that are to be taken dynamically. But the values are not getting updated in database.
column names are co1,co2....
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
PreparedStatement pstmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/netbeans","root","");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM colo");
rs = st.executeQuery("SELECT COUNT(*) FROM colo");
// get the number of rows from the result set
rs.next();
int rowCount = rs.getInt(1);
//txt_ans.setText(String.valueOf(rowCount));
int num_1 =300;
int num_2 =200;
int num_3 =300;
int num_4 =400;
String value = null;
int value1 ;
for(int i=1;i<=rowCount;i++)
{
String sql =("SELECT * FROM colo WHERE id = '"+i+"'");
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
while(rs.next())
value = rs.getString("co1");
//txt_ans.setText(String.valueOf(value));
String x = "co2";
if(value.equals("lo1"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+x+"' = '"+num_1+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else if(value.equals("lo2"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+ x +"' = '"+num_2+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else
{
value1 = 9009;
txt_ans.setText(String.valueOf(value1));
}
}
The problem is with using single quotes for column name i.e, like 'x', so just remove them as shown below:
String sql1 =("update colo set " + x + " = ? where id = ?");//no single quote for x
pstmt = conn.prepareStatement(sql1);
pstmt.setString(1, num_1);
pstmt.setString(2, i);
int r = pstmt.executeUpdate(sql1);
Also, always use prepareStatement's setString, etc.. methods for setting the values which is recommended.
Apply the same concept for the other query inside the else if(value.equals("lo2")) block as well.
I want to retrieve all the name and the number of row from MySQL to java. So far I only able to retrieve the total row number but I only get the last name. What's wrong here ?
StaffManagement.java
adminAPI api= new adminAPI();
try {
int num= api.displayCheckBoxAndLabel();
String allName= api.displayName();
System.out.println(num+allName);
}
adminAPI
public int displayCheckBoxAndLabel() throws Exception // get the number of row
{
int count = 0;
String sql="Select count(*) AS adminID from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
count= rs.getInt("adminID");
}
ps.close();
rs.close();
conn.close();
return count ;
}
public String displayName() throws Exception // get all the name
{
String name = null;
String sql="Select name from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
name= rs.getString("name");
}
ps.close();
rs.close();
conn.close();
return name ;
}
You currently return a single String, and your method iterates all of the admin names (but terminates after the final row, so that's your result). Instead, build a List of names and return that. You could also use a try-with-resources close to close your Connection, Statement and ResultSet instances. Something like
public List<String> displayName() throws Exception // get all the name
{
String sql = "Select name from admin";
List<String> names = new ArrayList<>();
DatabaseConnection db = new DatabaseConnection();
try (Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString("name"));
}
}
return names;
}
This might be helpful
private String names[];
int i = 0;
while (rs.next()) {
names[i] = rs.getString("name");
i++;
}
Then you can use a for loop to return each name in StaffManagement.java
Ok, so I'm having some difficulties in returning multiple results on this query in Java
public String getActive() throws SQLException
{
Connection con = DBConnect.getConnection();
String numeUser = "";
String sql=("select NUME from agents WHERE ACTIV = ? AND FILIALA = ? ");
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.setString(2, "MS10");
ResultSet rs = pstmt.executeQuery();
while(rs.next())
{
numeUser = rs.getString("NUME");
}
rs.close();
con.close();
return numeUser;
}
I heard something about that i can return the result with split() method or tokenizer but I don't seem to return the right result.
Agenti q2 = new Agenti();
String str1 = q2.getActive();
StringTokenizer stk1 = new StringTokenizer(str1);
String[] s1 = new String[0];
int i = 0;
while(stk1.hasMoreElements())
{
s1[i] = (String) stk1.nextElement();
i++;
}
System.out.println(s1[0]);
This is my tokenizer code. Can someone help me a little, please?
This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 6 years ago.
`
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
PreparedStatement pst = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
String query1 = "SELECT Name FROM Employee WHERE Name=?";
pst = conn1.prepareStatement(query1);
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String name = "";
int count = 0;
while(rs.next()){
title = rs.getString("name");
pst.setString(1, title);
rs1 = pst.executeQuery();
while(rs1.next()){
count++;
if(count % 100 == 0)
System.out.println(count);
}
}
System.out.println(count);
}
}
`
I am selecting value from the very large database based on some value from other database . I am running my select query in a while loop. After running my java code after getting many result , i am getting
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Communications link failure exception.
I have no idea why this is happening. If you guys have any idea please help
I already read the old questions based on this exception but none of them helps.
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
PreparedStatement pst = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String title = "",query1="";
StringBuffer newQuery = new StringBuffer("SELECT Name FROM Employee WHERE ");
int count = 0;
long nameCount = 0L;
while(rs.next()){
nameCount++;
title = rs.getString("name");
query1 = "Name=? or";
pst = conn1.prepareStatement(query1);
pst.setString(1, title);
newQuery.append(pst.toString().substring(pst.toString().indexOf('N'), pst.toString().length())+" ");
}
if ( nameCount > 0 ){
String Query = newQuery.toString().substring(0,newQuery.toString().length() - 3);
rs1 = conn1.createStatement().executeQuery(Query);
while(rs1.next()){
count++;
if(count % 50 == 0)
System.out.println(count);
}
}
}
}
Using PreparedStatement solves the problem of SQL Injection attack. Now the code is working.
I think this code is optimized, but it may have some syntax error:
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
//String query1 = "SELECT Name FROM Employee WHERE Name=?";
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String name = "";
StringBuffer newQuery = new StringBuffer("SELECT Name FROM Employee WHERE");
int count = 0;
long nameCount = 0L;
while(rs.next()){
nameCount++;
title = rs.getString("name");
newQuery.append(" Name='" + title + "' or");
}
if ( nameCount > 0 ){
newQuery = newQuery.subString( newQuery.length() - 3);
rs1 = conn1.createStatement.executeQuery( newQuery );
while(rs1.next()){
count++;
if(count % 100 == 0)
System.out.println(count);
}
}
}
}
Link failure may be because of so many query execution. Hence I have made it to fire only one or two queries, and you will get all your results.
In the below code I am copying resultset content to arraylist. First part of the wile loop i.e while(RS.next()) is returing the results but when cursor moves to
Next while loop i.e while(SR.next()) I am getting "result set is closed". Please help me where I am doing mistake.
String SSQ = "select DISTINCT S_NUMBER from OTG.S_R_VAL" +
" WHERE R_TS = (SELECT MAX(R_TS) FROM OTG.S_R_VAL) order by S_NUMBER";
String SDS = "SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN" +
"(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO )";
String SSR = "SELECT DISTINCT S_NO FROM OTG.R_VAL where S_NO != 'NULL' order by S_NO";
String SSO = "Select O_UID from OTG.OPTY where C_S_NO IN" +
"( SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO ))";
//Statement statement;
try {
connection = DatabaseConnection.getCon();
statement = connection.createStatement();
statement1 = connection.createStatement();
statement2 = connection.createStatement();
statement3 = connection.createStatement();
statement4 = connection.createStatement();
ResultSet RS = statement1.executeQuery(selectQuery);
ResultSet DS = statement2.executeQuery(Distinct_SiebelNo);
ResultSet SR = statement3.executeQuery(SiebelNo_Rev);
ResultSet SO = statement4.executeQuery(selected_OppId);
ArrayList<String> RSList = new ArrayList<String>();
ArrayList<String> SRList = new ArrayList<String>();
/* ResultSetMetaData resultSetMetaData = RS.getMetaData();
int count = resultSetMetaData.getColumnCount();*/
int count=1;
System.out.println("******count********"+count);
while(RS.next()) {
int i = 1;
count=1;
while(i < count)
{
RSList.add(RS.getString(i++));
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
/* ResultSetMetaData resultSetMetaData1 = SR.getMetaData();
int count1 = resultSetMetaData1.getColumnCount();*/
int count1=1;
while(SR.next()) {
int i = 1;
while(i < count1)
{
SRList.add(SR.getString(i++));
}
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}SR.close();
connection.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The logic of each loop is flawed.
int count=1;//Count is being set to one
while(RS.next()) {
int i = 1;//i is being set to one
count=1;//count again set to one
while(i < count) //condition will always fail as one is never less than one
{
RSList.add(RS.getString(i++));//Code is never Reached
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
The second while is not needed. Just use this:
int count = 1;
while(RS.next()) {
RSList.add(RS.getString(count++));
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
EDIT
int count1=1;
while(SR.next()) {
SRList.add(SR.getString(count1++));
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}
EDIT 2:
for (String s : RSList)
for(String s1 : SRList)
if (s.equals(s1))
//Do what you need
You are using the first resultset (RS) in the second loop (System.out.println line)