Usage of Multiple Queries to get data from different tables - java

I am new to DATABASE and MYSQL so don't have much experience or knowledge with handling queries
I have two tables students and login in MYSQL database, they both have 1:1 relation, Primary key of student is a foreign key in login.
So login table has both Student_ID(FK) and Password
I want to run a query in a JAVA program that will check the id and password entered by the user in login table and then return the matching student object data from student table
So far this is what I am doing for login the user put in username and password
public Student validate_Student(String s, String t)
{
int w = Integer.parseInt(s);
int q = 0;
String iD = "";
Student obj = new Student();
String query = "SELECT * FROM login WHERE Student_ID = " + w + " and Password= " + t;
try
{
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
iD = rs.getString("Student_ID"); //matching record
}
int i = Integer.parseInt(iD); // check the previously searched matching record in student table
String query1 = "SELECT * FROM student WHERE ID = " + i;
ResultSet rs1 = stmt.executeQuery(query);
while (rs1.next()) {
obj.setID(rs1.getString("ID"));
obj.setName(rs1.getString("NAME"));
obj.setAddress(rs1.getString("ADDRESS"));
obj.setPhone(rs1.getString("PHONE_NO"));
obj.setEmail(rs1.getString("EMAIL"));
obj.setDOB(rs1.getString("DOB"));
obj.setDegree(rs1.getString("DEGREE"));
}
}
catch(SQLException e)
{
System.out.println("Problem in Query");
e.printStackTrace();
}
return obj;
}
I am not quite sure how to use UNIONS in the query

Below query will return student details whose login credentials match.
SELECT s.* FROM student s JOIN login l on s.id = l.Student_ID WHERE l.Student_ID = " + w + " and l.Password= '" + t + "'";
Join student table to login table using one to one relation s.id = l.Student_ID where s is the alias for student table and l for login table.
to return only student details use s.* in select statement.

Related

sql for update "ERROR: column "used" of relation "account" does not exist" even though it does

I have used this method without using the join in the query and it was working as expected. But I added a inner join and now it can't update the "used" column
public HashMap<String, Comparable> getPhoneNumberAndMarkAsUsed() {
String[] colNames = { "phone_number.id", "phone_number.phone_number",
"phone_number.account_id", "phone_number.used AS used",
"(now() AT TIME ZONE account.timezone)::time AS local_time" };
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from account INNER JOIN phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update";
HashMap<String, Comparable> account = new HashMap<String, Comparable>();
try (Connection conn = DriverManager.getConnection(url, props); // Make sure conn.setAutoCommit(false);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(query)) {
conn.setAutoCommit(false);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1)
System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue + " " + rsmd.getColumnName(i));
}
// Get the current values, if you need them.
account.put("phone_number", rs.getString("phone_number"));
account.put("account_id", rs.getLong("account_id"));
rs.updateBoolean("used", true);
rs.updateRow();
}
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
the loop prints the following
7223 id, 10001234567 phone_number, 1093629 account_id, f used, 23:32:42.502472 local_time
accourding to the output above, then I am use that column "used" is part of the ResultSet. But I get the following Exception
org.postgresql.util.PSQLException: ERROR: column "used" of relation "account" does not exist
This is the query when printed
select phone_number.id, phone_number.phone_number, phone_number.account_id, phone_number.used AS used, (now() AT TIME ZONE account.timezone)::time AS local_time from account INNER JOIN phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update
used belongs to the phone_number table not the account table. How can this be resolved?
here is the problem in your code:
rs.updateBoolean("used", true);
this statement will try to update the data of table through resultset but to do that you cannot user join and also there is one problem.
As you are updating via resultset it will try to update account table and if we find used column is account table then error occurs.
so your code is trying to find column "used" in account table but it is not there.
try this one:
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from phone_number INNER JOIN account phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update";

Why select statement always return the last inserted values?

When I try to Select a record using Prepared Statement it always giving me a last inserted values that I recently add.
First what did I do is to search a record in my first table. If the record is exist the foreign key table will populate the values. My Primary and Foreign Key tables works well. The values populating appropriately to their corresponding components but it's not giving me the right values. Any help?
This is the Primary Key table referencing Foreign Key table which is the 2nd table.
Select Query:
String searchSECTIONNAME = "SELECT * FROM allsections_list WHERE SECTION_NAME = ?";//1st Select Statement
String searchSECTIONSETTINGS = "SELECT allsections_list.`SECTION_ID`, allsections_settings.ADVISER_ASSIGNED, allsections_settings.SECTION_POPULIMIT,\n" +
"allsections_settings.ROOM_ASSGN, allsections_settings.YRLEVEL_ASSGN, allsections_settings.SCHOOL_YEAR, allsections_settings.SESSION_ASSIGNED\n" +
"FROM allsections_list\n" +
"RIGHT JOIN allsections_settings\n" +
"ON allsections_list.`SECTION_ID`=allsections_settings.`SECTION_ID`";//2nd Select Statement
So what did I do here is join the SECTION_NAME column to Foreign Key table using Right Join. If the record exist it will join the two tables.
Code:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String searchSection = Section_SearchSection_Textfield.getText();
try (Connection myConn = DBUtil.connect();
PreparedStatement myFirstPs = myConn.prepareStatement(searchSECTIONNAME);)
{
myFirstPs.setString(1, searchSection);
try (ResultSet myFirstRs = myFirstPs.executeQuery())
{
int resultCounter = 0;
while (myFirstRs.next())
{
String mySectionName = myFirstRs.getString(2);//Get the value of SECTION_NAME
Section_SectionName_TextField.setText(mySectionName);
Section_SectionName_TextField.setEnabled(true);
try (PreparedStatement mySecondPs = myConn.prepareStatement(searchSECTIONSETTINGS))
{
try (ResultSet mySecondRs = mySecondPs.executeQuery())
{
while (mySecondRs.next())
{
String myAdviserAssigned = mySecondRs.getString(2);
Section_Student_Limit_ComboBox1.setSelectedItem(myAdviserAssigned);
Section_Student_Limit_ComboBox1.setEnabled(true);
String mySectionPopulation = mySecondRs.getString(3);
Section_Student_Limit_ComboBox.setSelectedItem(mySectionPopulation);
Section_Student_Limit_ComboBox.setEnabled(true);
String myRoomAssigned = mySecondRs.getString(4);
Section_Room_Assignment_ComboBox.setSelectedItem(myRoomAssigned);
Section_Room_Assignment_ComboBox.setEnabled(true);
String myYearLevelAssigned = mySecondRs.getString(5);
Section_Session_Level_ComboBox.setSelectedItem(myYearLevelAssigned);
Section_Session_Level_ComboBox.setEnabled(true);
String mySchoolYear = mySecondRs.getString(6);
Section_SchooYear_ComboBox.setSelectedItem(mySchoolYear);
Section_SchooYear_ComboBox.setEnabled(true);
String mySessionAssigned = mySecondRs.getString(7);
Section_Session_Settings_ComboBox.setSelectedItem(mySessionAssigned);
Section_Session_Settings_ComboBox.setEnabled(true);
resultCounter++;
}//end of loop mySecondRs (ResultSet)
}//end of try mySecondRs (ResultSet)
}//end of try mySecondPs (PreparedStatement)
}//end of loop myFirstRs (ResultSet)
if (resultCounter == 1)//If exist
{
JOptionPane.showMessageDialog(null, "Data Found");
}
else//If not exist
JOptionPane.showMessageDialog(null, "No Data Found");
}//end of try myFirstRs (ResultSet)
}//end of try myFirstPs (PreparedStatement)
catch (SQLException e)
{
DBUtil.processException(e);
}//end of catch
}
As you can see here. In my first ResultSet myFirstRs when I search a existing SECTION_NAME the foreign key values will populate. If something something in my loop correct me. Thanks in advanced!
Update!
I add a ORDER BY clause in my 2nd Select Query. Because without this the database will return what it wants, so what did I do is modify the query and add the ORDER BY clause like this:
String searchSECTIONSETTINGS = "SELECT allsections_list.`SECTION_ID`, allsections_settings.ADVISER_ASSIGNED, allsections_settings.SECTION_POPULIMIT,\n" +
"allsections_settings.ROOM_ASSGN, allsections_settings.YRLEVEL_ASSGN, allsections_settings.SCHOOL_YEAR, allsections_settings.SESSION_ASSIGNED\n" +
"FROM allsections_list\n" +
"RIGHT JOIN allsections_settings\n" +
"ON allsections_list.`SECTION_ID` = allsections_settings.`SECTION_ID`" +
"ORDER BY allsections_list.SECTION_ID";
Still giving me wrong values when I run the project. I tried to run this in NetBeans query and giving me a values in a ASC order.
I just found a simplest solution. I joined the two tables using Right Join.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String searchSection = Section_SearchSection_Textfield.getText().replace("!", "!!").replace("%", "!%").replace("_", "!_")
.replace("[", "![");
String searchSECTIONSETTINGS = "SELECT allsections_list.SECTION_ID as 'ID', allsections_list.SECTION_NAME as 'Section Name', allsections_settings.ADVISER_ASSIGNED as 'Adviser', allsections_settings.SECTION_POPULIMIT as 'Population',\n" +
"allsections_settings.ROOM_ASSGN as 'Room', allsections_settings.YRLEVEL_ASSGN as 'Year Level', allsections_settings.SCHOOL_YEAR as 'School Year', allsections_settings.SESSION_ASSIGNED as 'Session'\n" +
"FROM allsections_list\n" +
"RIGHT JOIN allsections_settings\n" +
"ON allsections_list.SECTION_ID = allsections_settings.SECTION_ID\n" +
"WHERE SECTION_NAME LIKE ? ESCAPE '!'\n" +
"ORDER BY allsections_list.SECTION_ID";
if (searchSection.isEmpty())
{
JOptionPane.showMessageDialog(null, "Please fill up this fields");
}
else
try (Connection myConn = DBUtil.connect();
PreparedStatement myFirstPs = myConn.prepareStatement(searchSECTIONSETTINGS);)
{
myFirstPs.setString(1, "%" +searchSection +"%");
try (ResultSet myFirstRs = myFirstPs.executeQuery())
{
int resultCounter = 0;
while (myFirstRs.next())
{
String name = myFirstRs.getString(2);
sectionJTable.setModel(DbUtils.resultSetToTableModel(myFirstRs));
resultCounter++;
}//end of loop myFirstRs (ResultSet)
if (resultCounter > 0)//If exist
{
JOptionPane.showMessageDialog(null, "Data Found");
}
else//If not exist
JOptionPane.showMessageDialog(null, "No Data Found");
}//end of try myFirstRs (ResultSet)
}//end of try myFirstPs (PreparedStatement)
catch (SQLException e)
{
DBUtil.processException(e);
}//end of catch
}

Ambiguous column using JDBC but query works fine in database

I am connecting to a SQLite database through java using JDBC.
Schema:
WorkInfo(id, job, salary)
Person(id, name)
This query below runs fine in my database, but when I try it with JDBC:
ResultSet rs = statement.executeQuery("select * from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("Person.id")); //column does not exist
System.out.println("name: " + rs.getString("name")); //works fine
Output:
If using person.id: no such column: 'person.id'
Without specifying: ambiguous column name 'id'
I've tried using both WorkInfo and Person and using aliases but it keeps throwing the same ambigious column name (if left as id) or column does not exist.
It's always a good practice to explicitly retrieve the columns you want. I would change the query to be:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id, person.name from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt(4));
System.out.println("name: " + rs.getString(5));
In this case, you can use the column index instead of the label.
Or using the AS clause:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id as personId, person.name as personName "
+ "from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt("personId"));
System.out.println("name: " + rs.getString("personName"));
After a day of working on this, I achieved it by using resultSet.getMetaData().
private int getIndexFromMeta(String column) {
try {
ResultSetMetaData meta = resultSet.getMetaData();
String[] subs = column.split("\\.", -1);
String tableName = subs[0];
String columnName = subs[1];
for (int i = 1; i <= meta.getColumnCount(); i++) {
if (meta.getTableName(i).equals(tableName) && meta.getColumnName(i).equals(columnName)) {
return i;
}
}
} catch (SQLException e) {
Log.trace(e);
}
return 0;
}
It seems like the ResultSet you're getting back holds the following columns:
id
name
id
job
salary
You have two columns named "id" (none named "Person.id"), so when you try to get its' value you either
Ask for "id" which is ambiguous (which id?)
Ask for "Person.id" which does not exist
Simply try specifying in your query the columns you want and giving them unique aliases. For example:
ResultSet rs = statement.executeQuery("select Person.id AS 'personid', name from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("personid"));
System.out.println("name: " + rs.getString("name"));

How to use user input as parameter for query?

So I'm very new to java and SQL and they are my first programming languages. I am trying to do some work with JDBC. I want to allow for a user to input an id and return a query based on the variable. If someone could at least point me in the right direction... Here is the code I'm starting with. Mind you its crude but just trying to get a working piece of code so I can better implement it in my main class.
Scanner input = new Scanner(System.in);
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Derek\\Documents\\Databases\\example.sqlite");
Statement stat = conn.createStatement();
PreparedStatement prep1 = conn.prepareStatement(
"insert into MedType values (?, ?);");
PreparedStatement prep2 = conn.prepareStatement(
"insert into Media values (?, ?,?, ?,?, ?);");
System.out.print("Please choose a database(MedType or Media): ");
String db=input.next();
if(db.equalsIgnoreCase("MedType"))
{
System.out.print("Enter in ID: ");
String answer1 = input.next();
System.out.print("");
String answer2 = input.nextLine();
System.out.print("Enter in Description: ");
String answer3 = input.nextLine();
prep1.setString(1, answer1);//add values into cell
prep1.setString(2, answer3);
prep1.addBatch();//add the columns that have been entered
}
conn.setAutoCommit(false);
prep1.executeBatch();
prep2.executeBatch();
conn.setAutoCommit(true);
System.out.print("Please Enter Query(One or All): ");
String q=input.next();
ResultSet rs= stat.executeQuery("select * from MedType;");
if(q.equalsIgnoreCase("all")){
while (rs.next()) {
System.out.print("All ID = " + rs.getString("ID") + " ");
System.out.println("All Description = " + rs.getString("Description"));}
}
if(q.equalsIgnoreCase("one")){
System.out.print("Enter ID: ");
}
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+ (rs.getString("ID")+"="+idNum));
if(q.equalsIgnoreCase("one")){
while (oneRs.next()) {
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
rs.close();
oneRs.close();
conn.close();
}
}
ResultSet oneRs = stat.executeQuery("select * from MedType Where"+
(rs.getString("ID")+"="+idNum));
This is where I'm having trouble. Creating a statement that says return something from the table if its id is equal to the user input. I get this error
Exception in thread "main" java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near "=": syntax error)
In query you are trying to access single row by passing id.. In generally sql query we are using to access single row by passing some information. select * from MedType where id=3 this query will return you result set containing row or rows with id equals to 3.
so in your code your query should be select * from MedType where id="+idNum+" if in your db id column is int.
and keep this query in if block only i.e
if(q.equalsIgnoreCase("one"))
{
System.out.print("Enter ID: ");
int idNum=input.nextInt();
ResultSet oneRs = stat.executeQuery("select * from MedType Where id="+idNum+" ");
// if id column in db is int if it is string then use id='"+idNum+"'
while (oneRs.next())
{
System.out.print("ID = " + oneRs.getString("ID") + " ");
System.out.println("Description = " + oneRs.getString("Description"));
}
}
In your query:
select * from MedType Where"+ (rs.getString("ID")+"="+idNum
you seem to try to grab the ID from the first resultset where you return all tuples.
That won't work as in the where clause the ID won't be there (as there is no result right now without rs.next()). If there was a result then you potentially have something like 'where 3 = 3' (3 would be the result of the previously returned value. Have you tried simply to use:
select * from MedType Where ID = " + idNum
Hope that makes sense.

using arraylist inside mysql select statement

I have a login arraylist where i have stored users loginid using following mysql query
Code:
query = "select LoginID from issuedeposit id where id.DueDate < CURDATE()";
result = statement.executeQuery(query);
while(result.next())
{
String loginid = result.getString(1);
loginarray.add(loginid);
}
now I want to use the loginid values stored in the above arraylist to fetch users emailid form other table. I am using following query
Code:
for(int i=0;i<=loginarray.size();i++)
{
res = statement1.executeQuery("select EmailID form studentaccount sa where sa.LoginID = '"+ loginarray.get(i) +"' ");
String email = res.getString(1);
emailarray.add(email);
}
but am getting error in the above query. So have i correctly used the for loop or it should be used inside the query...?
I am using JDBC and MySql
res = statement1.executeQuery("select EmailID form studentaccount sa
where sa.LoginID = '"+ loginarray.get(i) +"' ");
Should be
res = statement1.executeQuery("select EmailID FROM studentaccount sa
where sa.LoginID = '"+ loginarray.get(i) +"' ");

Categories

Resources