Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to display a row in jtextarea each time a new name is entered. Suppose a user writes "Paul" in a jtextfield, based on SQLite, it should show it's corresponding response, which will be "Smith". I have a database with several names and no matter what I write, say "Peter", it shows "Smith" where it should have shown "Parker". What I want is each time a user enters a name, it's corresponding surname should appear.

What I have tried:

I have tried this code but only the first row from the db appears:
EDIT: This is the method I used
public void fetch() throws Exception{	
	Connection con = null;
	con = sqliteConnection.sqliteConnector();
	PreparedStatement pst = null;
	ResultSet rs = null;
	try
	    {
		String quest=userInputField.getText().toLowerCase().trim().toString();
			String sql = "select * from user where name LIKE '% %'";
			pst = con.prepareStatement(sql);
			//pst.setString(1, quest);//getting array index out of bounds 0
			rs = pst.executeQuery();
			if(rs.next()){ 
				String ans = rs.getString("answer");
				textarea.append(ans +"\n");   
				
			}else {
            	  textarea.append("Nothing was found." +"\n");  
            }
			
			System.out.println("Succesfully retrieved data from bcsdb");
			if (pst != null) pst.close();
            System.out.println("PST was successfully closed!");
            if (rs != null) rs.close();
            System.out.println("PS was successfully closed!");
            if (con != null) con.close();
            System.out.println("Con was successfully closed!");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
	}


Thanks in advance!
Posted
Updated 19-Jul-18 19:09pm
v5

1 solution

Your SQL statement will match all names. You need to modify it with a parameter that specifies the name entered by the user.
 
Share this answer
 
Comments
Member 13780097 17-Jul-18 0:27am    
Can you show me how please? I tried with pst.setString(1, variable_name) but I'm having his error: java.lang.ArrayIndexOutOfBoundsException: 0
Richard MacCutchan 17-Jul-18 2:51am    
You need to show the code and explain where the error occurs. See Using Prepared Statements (The Java™ Tutorials > JDBC(TM) Database Access > JDBC Basics)[^] for more details.
Member 13780097 17-Jul-18 23:47pm    
I'm having an error at this line : pst.setString(1, userInputField.getText().toLowerCase().trim());
Richard MacCutchan 18-Jul-18 1:13am    
I cannot see anything obvious in that statement. Please edit your question and show more of the code.
Member 13780097 20-Jul-18 1:09am    
I posted the full method I used. Hope it can help you to find a solution for me

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900