Tuğcan Demir
Tuğcan Demir

Reputation: 113

How to access a specific row in MySQL using Java

When I write a name as a user, I need to access the surname for this name which is already in database. For example:

Enter a name: beste

beste's surname is: ozcaglar

When I execute my code I can't see any surname as output.

In my database, I have name, surname and no (Auto-Incremented) columns.

import java.sql.*;
import java.util.*;

public class ConnectionMySQL {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a name: ");
        String isim = scan.next();

        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/student","root","");
            //System.out.println("Connection success");
            String query= "SELECT surname FROM student_table WHERE name='isim'";
            Statement stm =conn.createStatement();
            ResultSet rs= stm.executeQuery(query);

            while (rs.next()) {
                System.out.println("Name: " + rs.getString("name")+ " Surname: "+rs.getString("surname"));
            }
        }
        catch (Exception e) {
            System.err.println(e);
        }
    }
}

Upvotes: 1

Views: 4149

Answers (2)

Marcos Delgado
Marcos Delgado

Reputation: 197

You can follow this:

import java.sql.*;
import java.util.*;
public class test4 {
public static void main(String[] args) {
    @SuppressWarnings("resource")
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a name: ");
    String isim = scan.next();
    try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
            System.out.println("Connection success");
            String query = "SELECT * FROM users WHERE surname='" + isim + "'";
            Statement stm = conn.createStatement();
            ResultSet rs = stm.executeQuery(query);
            while (rs.next()) {
                String fName = rs.getString(1);
                String sName = rs.getString(2);
                System.out.println("Name: " + fName + " Surname: " + sName);
            }
        } catch (Exception e) {
        System.err.println("Error");
        }
    }
}

Upvotes: 1

obe
obe

Reputation: 7788

The error means that the table doesn't have a column that is called "isim".

Maybe you meant to write:

SELECT surname FROM student_table WHERE name='isim'

?

EDIT (following the comments):

query = "SELECT surname FROM student_table WHERE name='" + isim + "'"

However this should not be used in a real-world application for security reasons (it allows SQL injection attacks).

In actual production code you should either escape input strings, or use parameterized queries...

Upvotes: 0

Related Questions