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.
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.
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.
hi my program work in back ground and show different message from database
in specific time the problem always show the same row
//////
**upload code **
public void myMethod(){
long startTime = System.currentTimeMillis();
int counter = 0;
while(true) {
if((System.currentTimeMillis() - startTime ) == 5000){
try{
String host = "jdbc:derby://localhost:1527/Quet";
String uName = "eenas";
String uPass= "2234";
con = DriverManager.getConnection( host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery( "SELECT * from EENAS.EENAS");
rs.next();
int id_col = rs.getInt("ID");
String id =Integer.toString(id_col);
String me=rs.getString("MESSAGE");
System.out.print(me);
rs.close();
}
catch(SQLException err)
{
JOptionPane.showMessageDialog(null, err);
}
startTime = System.currentTimeMillis();
continue; }
else{ continue; } } }
upload code
the can solve this problem by using arrayList to save all data, your program now show only that last one because they change their value every time, the solution like this,
public void DoConnect( ) {
try{
String host = "jdbc:derby://localhost:1527/Quet";
String uName = "eenas";
String uPass= "2234";
con = DriverManager.getConnection( host, uName, uPass);
stmt = con.createStatement();
rs = stmt.executeQuery("select * from EENAS.EENAS");
List<String> PMessage = new ArrayList<String>();
List<Integer> id_col = new ArrayList<Integer>();
while(rs.next()){
id_col.add(rs.getInt("ID"));
PMessage.add(rs.getString("MESSAGE"));
jTextArea1.setText(PMessage);
}
rs.close();
stmt.close();
con.close();
}
catch(SQLException err)
{
JOptionPane.showMessageDialog(null, err);
}
}
I didn't run the code on my machine but this is the logic can solve the problem.
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?