Displaying data from two tables in java mysql - java

i want to display messages with the sender name. The outer while loop is working fine but there is some problem in the inner while loop. I have tried a lot to figure out but got no result. Can anyone help me? I'll very thankful.
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class Messages extends Login {
static Scanner in = new Scanner(System.in);
public static void main(String args[]) throws Exception{
boolean isLoggedin = login();
String msg = "";
String senName = "";
if(isLoggedin) {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?verifyServerCertificate=false&useSSL=false", "root", "");
Statement st = con.createStatement();
Statement st1 = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM chat");
ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
while(rs.next()) {
int dbRecID = rs.getInt("reciever_id");
if(dbRecID == user_id) {
msg = rs.getString("message");
int dbSenID = rs.getInt("sender_id");
while(rs1.next()) {
int senID = rs1.getInt("id");
if(senID == dbSenID) {
senName = rs1.getString("name");
}
}
System.out.println(senName+" sent you a message: "+msg);
}
}
}
else {
System.out.print("Login Unsuccessful");
}
}
}
Output
Ali Ahmed sent you a message: How are you?
Ali Ahmed sent you a message: Hi!
Required Output
Ali Ahmed sent you a message: How are you?
Hamza sent you a message: Hi!

The issue comes from the two nested while loops.
The query ResultSet rs1 = st1.executeQuery("SELECT * FROM data"); is executed just once.
The first time you loop on while(rs.next()) you will fetch the whole content of rs1 to check if the sender id is the right one.
Then on the second iteration on while(rs.next()) because rs1 has been already fetched while(rs1.next()) wil return false.
In order to have your code working you should move the execution of the second query to get something like this:
while(rs.next()) {
...
ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
while(rs1.next()) {
...
}
...
}
But I think that it would be a better solution to make just one SQL
request joining the datas of the two tables and including the where
condition.

Related

java.sql.SQLException: No current row in the ResultSet

I'm using the jtbs.jdbc.Driver to verify that a proxy number is stored in my MySQL database.
The problem is that whenever I try to copy the curtain row from the table and put it in my ResultSet, the error says that
there is no current row in the ResultSet
The error is at line 31 String value = result.getString(i);
i have been looking all over the web for answers but none of them seem to help my specific predicament.
UP DATE
so far i added a while(result.next()) and it basically dose nothing the while(result.next()) dose not execute.
Here's my code!!!
package dataBata;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class apples {
ArrayList<String> myList = new ArrayList<String>();
String proxNumber = "2435847564";
String usersName = "user";
String password = "pass";
public void wrightMatchdb(){
Connection conn = null;
String url = "jdbc:jtds:sqlserver://localhost:1433/model";
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(url, usersName, password);
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("select replace(PROXID , ' ','') PROXID ,FIRST_NAME from OKWC_IDCARDS where PROXID = '" + proxNumber + "'");
System.out.println("hello");
while(result.next()){
for(int i=1;i<=6;i++){
System.out.println("hello2");
String value = result.getString(i);
if(result.getString(i) != null){
value = value.replace(" ","");
myList.add(value);
}
String userProx=myList.get(i);
String userFName=myList.get(i+1);
JOptionPane.showMessageDialog(null, userProx + " has a match for", "hi " + userFName, JOptionPane.DEFAULT_OPTION);
}
System.out.println("hello3");
};
System.out.println("hello4");
statement.close();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (conn != null) try { conn.close(); } catch(Exception e) {}
}
}
public static void main(String[] args){
apples A = new apples();
A.wrightMatchdb();
}
}
You need to call result.next() before calling result.getString(i)
Moves the cursor forward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
As far as I can see, your query returns only 2 columns so if you call result.getString(i), make sure that i is either 1 or 2 otherwise you will get an exception.

Java code not returning the proper table from mysql

I have this testing code that im trying to use to print the result set from my database table in MySQL. Right now It is printing the following.
Connecting database...
Database connected!
com.mysql.jdbc.StatementImpl#6f5f1a42
I am not sure why it is not printing the table columns and values in my db.
here is the code.
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
class Test {
public static void main (String [] args) throws SQLException {
// jdbc:mysql://localhost:3306/mysqldb
String url = "jdbc:mysql://localhost:3306/mysqldb?useSSL=false";
String username = "joker";
String password = "joker";
System.out.println("Connecting database...");
Connection connection = null;
try {
connection = (Connection) DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
Statement stmt = (Statement) connection.createStatement();
ResultSet rs = stmt.executeQuery("Select * FROM pet");
System.out.println(rs.getStatement().toString());
stmt.close();
close(connection);
}
public static void close(Connection con){
if(con != null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
After your execute query, you should do something like this
while (rs.next()) {
System.out.println(rs.getInt("column name");)}
Change get operation by column data type. exp: rs.getString, rs.getDouble etc.
check this link for further information
From the docs, the ResultSet merely represents the returned data:
A table of data representing a database result set, which is usually
generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of
data. Initially the cursor is positioned before the first row. The
next method moves the cursor to the next row, and because it returns
false when there are no more rows in the ResultSet object, it can be
used in a while loop to iterate through the result set.
As such, you need to iterate through the result set if you are interested in the data returned from your query using the respective getters such as getString or getInt:
while (rs.next()) {
System.out.println(rs.getInt("Id"));
System.out.println(rs.getString("Name"));
}
You have to iterate over ResultSet
while (rs.next()) {
System.out.println(rs.getString("Col1")); // or rs.getString(0);
System.out.println(rs.getString("Col2"));
System.out.println(rs.getString("ColN"));
}
The output com.mysql.jdbc.StatementImpl#6f5f1a42 looks like the output of the default toString method inherited from the Object class. This is what gets invoked if the ResultSet class you're using doesn't implement its own toString method.
To print out rows and columns, you're going to have to iterate over the result set yourself. For example:
while (rs.next()) {
System.out.println(rs.getXXX(...));
...
}
To print the column names please use the below code
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
}
Similarly you may also fetch the data by either providing column number or name in a loop
ResultSet rs = st.getResultSet();
try {
while (rs.next()) {
int id = rs.getInt(1);
String userName = rs.getString(2);
String firstName = rs.getString(3);
String surname = rs.getString(4);
Timestamp timeReg = rs.getTimestamp(5);
// ... do something with these variables ...
}
} finally {
rs.close();
}
First up all you have to load the JDBC Driver Class using Class.forName().
Class.forName() load a given Java class in JVM and it also exit in your classpath.
the complete synatx is just like:- Class.forName("com.mysql.jdbc.Driver");

can't retrieve data from database

Problem was:
Can't get just inserted data from the table. From the error message it looks like it doesn't see the first column. I know the column is there and data was inserted. I checked database. I checked if column Number has some hidden space in name. No it doesn't.
Tried:
Debugged every line and everything was good together with inserting data to database.
Found the issue is almost at the end of the code:
rs1.next();
String s1 = rs1.getString(1);
I tried to write
rs1.first();
String s1 = rs1.getString(1);
or
rs1.first();
String s1 = rs1.getString("Number");
Below I posted my final code that is working correctly and I am able to insert data to the table and display on the browser.
package mypackage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.LinkedList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
#Path("/query")
public class CList {
private LinkedList<SMember> contacts;
public CList() {
contacts = new LinkedList();
}
#GET
#Path("/{CList}")
public Response addCLocation(#QueryParam("employeeId") String eId) throws SQLException{
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
PreparedStatement ps0 = null, ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try{
//Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
//Connection variables: dbPath, userName, password
con = (Connection)
DriverManager.getConnection(dbURL,"someusername","somepassword");
System.out.println("We are connected to database");
//SQL Statement to Execute
System.out.print(id);
s = con.prepareStatement("SELECT 1 FROM CList WHERE Number=?");
s.setString(1, eId);
rs = s.executeQuery();
//Parse SQL Response
if(!rs.next()) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) " +
"VALUES (?,?,?,?)");
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhone());
ps.executeUpdate();
ps = con.prepareStatement("SELECT Number, First_Name,
Last_Name, Phone_Number FROM CList
WHERE Number=" + eId);
rs1 = ps.executeQuery();
while(rs1.next()){
result = "[Added contact to contact list.
Number: " + rs1.getString(1) +
"][First_Name: " + rs1.getString(2) +
"][Last_name: " + rs1.getString(3) +
"][Phone_Number: " + rs1.getString(4) +
"]\n";
}
}
else {
result = "[Contact is already on the list]";
}
}
catch(Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
//Close Database Connection
ps0.close();
ps.close();
con.close();
}
}
catch(Exception e) {
System.out.println(e);
}
//Return the Result to Browser
return Response.status(1000).entity(result).build();
}
Table
1234 number is unique and it is a number I want to get.
You see number should be unique. So far I am taking data from the SMember class and it always insers the same data. Purpose of my question is just to ge the information I inserted few seconds ago.
Also, there is SMember class that I didn't post here and in its constructor I initialize number, first name, last name, and phone number. Testing purpose.
I made all recommended changes but problem remains the same.
There is several issues here.
The solution to your question is that you do not let the database generate keys, that is why you cannot ask for the generated keys later.
Look at this line of your code:
ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name, Phone_Number) VALUES ('"+sm.getEmployeeID()+"', '"+sm.getFirstName()+"', '"+sm.getLastName()+"', '"+sm.getPhone()+"')", Statement.RETURN_GENERATED_KEYS);
You later want to retrieve the Number column's value as a generated key. You however do pass a value for that column, namely the return value of sm.getEmployeeID(). If you pass a value, it will not get generated (assuming that this column is defined in database as being auto incremented.
Fixing this however, will not solve everything as your code has quite a lot of issues. Let me list the ones I can directly spot:
You initialize your variable sm by creating a new object. But you will still not have values for employee id, first name, last name or phone number as you nowhere set those values to sm (or do you do that in the default constructor?).
You are trying to use a prepared statement, this is good, but you are actually not doing that, this is very bad as it openes the ground for SQL injection. Instead of creating the query string like you are doing, you should use a fixed string like e.g INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?) and then set the values on the statement before executing it. That way nobody can mess with your database through that statement (read up on SQL injection, just google it to see the issue you would introduce).
Your employee id seems to be the eId parameter of your method. You should use that also in your select statement to see if it is already in your database (use a prepared statement here also) and in your insert statement later when the id is not already in the database.
If you are checking for a specific id, then insert that specific id, it is quite useless to retrieve some generated id. You already have defined your unique identifier. Use that one!
Edit: As your code is kind of a mess, I have cleaned this stuff a bit and fixed the issues that I could directly find. Check if this is helping you:
public Response addCLocation(String eId) throws SQLException {
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
Statement s = null;
PreparedStatement ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try {
// Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
// Connection variables: dbPath, userName, password
con = DriverManager.getConnection(dbURL, "someusername", "somepassword");
System.out.println("We are connected to database");
s = con.createStatement();
// SQL Statement to Execute
System.out.print(id);
PreparedStatement alreadyThere = con.prepareStatement("SELECT 1 FROM CList WHERE Number = ?");
alreadyThere.setString(1, eId);
System.out.println("0");
// Parse SQL Response
int i = 0;
if (rs.next() == false) {
SMember sm = new SMember();
ps = con
.prepareStatement("INSERT INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) VALUES (?,?,?,?)");
ps.setString(1, sm.getEmployeeID());
ps.setString(2, sm.getFirstName());
ps.setString(3, sm.getLastName());
ps.setString(4, sm.getPhone());
ps.executeUpdate();
}
else {
result = "[Contact is already on the list]";
}
}
catch (Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
// Close Database Connection
s.close();
ps.close();
con.close();
}
}
catch (Exception e) {
System.out.println(e);
}
// Return the Result to Browser
return Response.status(200).entity(result).build();
}
You are getting this error because your first query is wrong it is returning an empty resultset.
Firstly,
rs = s.executeQuery("SELECT 1 FROM CList WHERE Number='id'");
the above line in your code is not correct it should be like this:
**rs = s.executeQuery("SELECT 1 FROM CList WHERE Number="+id);**
then the correct query will be fired to database.
Secondly,there is problem in following code
if(rs.next() == false) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO CList (Number, First_Name, Last_Name,
Phone_Number) VALUES ('"+sm.getEmployeeID()+"',
'"+sm.getFirstName()+"', '"+sm.getLastName()+"',
'"+sm.getPhone()+"')",
Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
In the above code you should initialize the SMember, object currently in query they are going as null also the when you are using PreparedStatement you should use the query like this:
**ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhoneNumber());**
The Query statement maybe an issue "SELECT 1 FROM CList WHERE Number='id'",In select statement your id is taken as a String.we need to replace with value.
-->Try like this {"SELECT 1 FROM CList WHERE Number="+id},
-->One more thing "select 1 from table name" will print 1 for no of rows avail for your condition.
So my suggestion is
{"SELECT * FROM CList WHERE Number="+id}
try This!!
"SELECT 1 FROM CList WHERE Number='id'"
It looks like you're trying to actually select records where the Number value is 'id'. That may be causing the error when you try to do the "rs.next()" command on an empty result set. Are you instead trying to do something like
"SELECT 1 FROM CList WHERE Number=' " . id . "'"? Where "id" is a variable?

Eclipse Compiler error saying connection variable cannot be resolved to a type

this is a Java Code i wrote in Eclipse to retrieve information from a MySQL Database.. But the Compiler is giving an error saying conn cannot be resolved to a type.. can anyone pls tel me what i may be doin wrng??
import java.sql.*;
public class plh {
static Connection conn=null;
static Statement s=null;
public static void main(String[] args){
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wonkashop","root", "");
String st= new String("select * from users;");
s= new conn.createStatement(st);//ERROR.. why??
}
catch (Exception e) {
System.out.println("Unable to connect to Database");
}
}
}
Here in the line
s= new conn.createStatement(st);//ERROR.. why??
there is no need for new keyword
like
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(credentials);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(st);
I had the same issue, and surfing by Internet triying to get a solution without successful I put these imports and it works for me.
import java.sql.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
I hope this can help more people.
Remove the new keyword from your line of code. You need to get the Statement as :
s= conn.createStatement(); // createStatement doesn't take a String argument
DriverManager.getConnection() already returns a Connection object , which you have referenced by the identifier conn , hence use it to get the Statement .
If you want to pass the sql query string , use a PreparedStatement instead of a Statement.
That is Connection#prepareStatement(sql).
Statement :
final String st= "select * from users;";
Statement s = conn.createStatement();
ResultSet rs = stmt.executeQuery(st);
PreparedStatement:
final String st= "select * from users;";
PreparedStatement preparedStatement = conn.prepareStatement(st);
ResultSet rs = preparedStatement.executeQuery();
change this line
s= new conn.createStatement(st);//ERROR.. why??
to
s= conn.createStatement();
Connection#createStatement
Returns a new default Statement object.
Just conn.createStatement();. Don't put new here, because you're not instantiating a class.
You should only write new before the name of a class, because it creates an object of that class. But here, conn is not the name of a class - it's just the name of a variable that references an existing object of some class.
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wonkashop", "root", "");
st= "select * from users";
s = conn.createStatement();// fixed
ResultSet rs = s.executeQuery(st);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String name = rs.getInt("name");
}
}

Looking up data in database from user

I am trying to let a user lookup a football result, and the database displays that result from the database, but i keep getting this error:
Exception in thread "main" java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
This is my "useFootballBean.java" bean:
package results;
import results.*;
import java.util.*;
import java.sql.*;
public class UseFootballBean
{
public static void main(String[] args)
throws SQLException, ClassNotFoundException
{
Scanner keyboard = new Scanner(System.in);
String home;
ResultsBean resultsBean = new ResultsBean();
System.out.print("\nEnter Team: ");
home = keyboard.next();
home = resultsBean.getHome(home);
if (home.equals(null))
System.out.println(
"\n*** No such Team ***");
else
System.out.println("\nTeam " + home);
}
}
This is my "resultsBean.java" bean
package results;
import java.sql.*;
public class ResultsBean
{
private Connection connection;
private Statement statement;
private ResultSet results;
public String getHome(String enter)
throws SQLException, ClassNotFoundException
{
String query;
String team = null;
connectAndCreateStatement();
query = "SELECT * FROM Results WHERE homeTeam = "
+ enter;
results = statement.executeQuery(query);
if (results.next())
team = results.getString("homeTeam");
connection.close();
return team;
}
private void connectAndCreateStatement()
throws SQLException, ClassNotFoundException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection(
"jdbc:odbc:FootballData","","");
statement = connection.createStatement();
}
}
I think you are missing the single quotes required in where clause of query while comparing against a string value. Here you go:
where keyword_name='"+keyword_name+"'"
query = "SELECT * FROM Results WHERE homeTeam = " + '"+ enter + "'";
Since your query parameter is a string, you need to enclose it in quotes:
"SELECT * FROM Results WHERE homeTeam = '" + enter + "'";
However, this is still a bad approach, because it leaves you vulnerable to SQL injection (Remember Bobby Tables?), and will break if the user enters a team name containing quote characters (like England's Greatest Team). Therefore, you should use a PreparedStatement (see Java tutorial).
You are missing single quotation in your Sql Query
query = "SELECT * FROM Results WHERE homeTeam = '"
+ enter+"'";
OR with PreparedStatement to accept quotation
PreparedStatement stmt = null;
String sql;
ResultSet rows=null
try {
sql = "select * from Results where homeTeam=?"
stmt = theConn.prepareStatement(sql);
stmt.setString(1, "Team with ' are permitted!");
rows = stmt.executeQuery();
stmt.close();
}
catch (Exception e){
e.printStackTrace();
}
finally { if (stmt != null) {
stmt.close();
}
Thanks

Categories

Resources