java: display the elements from a database - java

I wrote some java code to display database, when I run the code it gives me just the last element of database , but I wanna display all elements of table
the code :
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
What should I do? Can anyone please help me to display all values?
Thank you for helping me.

I think the problem is with your code that the value of puissance is overwritten every time you get the next element. Only the last value is returned. You should put the results into a list and return the whole list:
public List<String> RecupererPuissance() {
List<String> puissances = new ArrayList<String>();
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance = rs.getString("Power");
puissances.add(puissance);
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissances;
}

public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
rs.first();
int count=0;
while (rs.next()) {
System.out.println("count = "+count);
count+=1;
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
If you see count printed only 1 time :
it would mean that you have only 1 row in column Power
and you maybe referring to the wrong column in your code

Related

ERREUR : Unknown column 'Accessoires' in 'where clause'

My query is throwing up this error while i have column Accessoires in table categorie Can anyone see why?
public int rechercheParCat(String test) {
int idcat = 0;
try {
String query = "SELECT id_cat FROM categorie WHERE titre="+test;
PreparedStatement pst = cnx2.prepareStatement(query);
ResultSet rs = pst.executeQuery(query);
idcat = rs.getInt(1);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return idcat;
}
I FIXED IT LIKE THIS:
int idcat = 0;
try {
String query = "SELECT id_cat FROM categorie WHERE titre=? ";
PreparedStatement pst = cnx2.prepareStatement(query);
pst.setString(1, test);
ResultSet rs = pst.executeQuery();
rs.first();
idcat = rs.getInt(1);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return idcat;
}```
Using bound parameters with a prepared statement likely fixes your bug and also solves the severe security issue.
public int rechercheParCat(String test) {
int idcat = 0;
try {
String query = "SELECT id_cat FROM categorie WHERE titre = ?";
PreparedStatement pst = cnx2.prepareStatement(query);
pst.setString(1, test);
ResultSet rs = pst.executeQuery(query);
idcat = rs.getInt(1);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return idcat;
}
The likely reason your code has failed is that test was "Accessoires", so the resulting SQL statement was:
SELECT id_cat FROM categorie WHERE titre=Accessoires
when in fact it should have been:
SELECT id_cat FROM categorie WHERE titre='Accessoires'
Even if you added quotes to the concatenated statement, you'd still have a problem. Just imagine what happens if somebody passes a value with quotes, e.g. O'Connor. This will just break the code. But a more clever person can inject SQL clauses.

Using ResultSet to return string value from database but method skips the "Try" clause?

Why is my following code:
PrintWriter pw = response.getWriter();
pw.println(getValueOf(SQL, "lastName");
not printing anything after passing it into my method:
public static String getValueOf(String sql, String colName)
{
String result = "";
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
result = rs.getString(colName);
conn.close();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
In other words, why does it seem to be skipping the "try" clause entirely and just jumping to return the empty "" result at the end?
My SQL statment:
String SQL = "SELECT lastName FROM customers WHERE firstName=\"Bob\";";
I do have an entry for the person "Bob" (his lastname is "Mike") in my Customers table.
My Customers Table:
lastName / firstName / address / email
EDIT
It works correctly if I change the return type to "void" but I actually need a String value.
Alternate code:
public static void getValueOf(String sql, String colName, PrintWriter pw)
{
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
pw.println(rs.getString(colName)); // This does print out to the webpage as "Mike"
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Based upon your last edit, I would guess that you have more than one records.
So change your code to
if (rs.next()) {
result = rs.getString(colName);
}
And also, your code does not skip that try block

Read a reference cursor which returns a column of string values

I am trying to read ref cursors, which returns only one column, a list of string data.
How can I do it java? Do I have to iterate through each resultset or is there any way so that I could get the entire column in one go. I have 5 ref cursor from the procedure.
rs1= (ResultSet) callableStatement.getObject(1);
rs2= (ResultSet) callableStatement.getObject(2);
rs3= (ResultSet) callableStatement.getObject(3);
while(rs1.next()){
list1.add(rs1.getString(1));
}
while(rs2.next()){
list2.add(rs2.getString(1));
}
while(rs3.next()){
list3.add(rs3.getString(1));
}
May this can help :
ResultSet result=null ;
PreparedStatement pstmt = null;
ArrayList yourlist = new ArrayList();
try
{
String queryString = "select yourfield from ....";
result = pstmt.executeQuery();
while(result.next())
{
yourlist.add(result.getInt("yourfield")); //if you are returning varchar so use getString
}
}
catch (SQLException e){
System.out.println("Exception: " + e.toString() );
}
finally
{
if(result!=null)
result.close();
if(pstmt!=null)
pstmt.close();
}

How to get the list inside a resultset?

I make a query in my database and put the results in a resultset. I have 8 attributes in the resultset, and first 7 of them are strings, so i can take them by writing:
rs.getString(1), rs.getString(2) ... etc
Then at the index 8, i have an ArrayList. I try to take it and create new list with the values in it but i could not do it. Here is my code, you can see what i tried there in the commented out line:
public void loginCheck() {
try {
Bank bank = Bank.getBank();
ResultSet rs = queryDatabase();
if (rs.next()) {
// List<Account> a = (List<Account>) rs.getObject(8, ArrayList); DOES NOT WORK
Customer currentCustomer = new Customer(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7));
addToSession(currentCustomer);
rs.close();
DBConnect.disconnect(con);
FacesContext.getCurrentInstance().getExternalContext().redirect("main.xhtml");
} else {
rs.close();
DBConnect.disconnect(con);
}
} catch (SQLException | IOException e) {
}
}
private ResultSet queryDatabase() {
con = DBConnect.connect();
try {
PreparedStatement checkDB = (PreparedStatement) con.prepareStatement("SELECT * FROM users where identityNumber = ? AND password = ?");
checkDB.setString(1, identityNumber);
checkDB.setString(2, password);
ResultSet res=(ResultSet) checkDB.executeQuery();
return res;
} catch (Exception e) {
return null;
}
}
Edit: I have a Customer object with 8 attributes, first 7 of them are string and the last one is an ArrayList object. My resultset rs contains a Customer object, so i want to get this list from the resultset, i mean the accounts of this specific user
So how can i get this ArrayList in the resultset? Can anyone help?
Thanks
In your commented code you are missing .class, it should be:
List<Account> a = (List<Account>) rs.getObject(8, ArrayList.class);

Java - Getting Data from MySQL database

I've connected to a MySQL database, which contains four fields (the first of which being an ID, the latter ones each containing varchar strings).
I am trying to get the last row of the database and retrieve the contents of the fields so that I can set them to variables (an int and three strings) and use them later.
So far, I have the bare minimum to make the connection, where do I go from here? As you can see I have tried to write a SQL statement to get the last row but it's all gone wrong from there and I don't know how to split it into the separate fields.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
st.getResultSet().getRow();
con.close();
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.
UPDATE : rs.next
boolean next()
throws SQLException
Moves the cursor froward 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.
When a call to the next method returns false, the cursor is positioned
after the last row. Any invocation of a ResultSet method which
requires a current row will result in a SQLException being thrown. If
the result set type is TYPE_FORWARD_ONLY, it is vendor specified
whether their JDBC driver implementation will return false or throw an
SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method
next will implicitly close it. A ResultSet object's warning chain is
cleared when a new row is read.
Returns:
true if the new current row is valid; false if there are no more rows Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
reference
Something like this would do:
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
you can iterate over the results with a while like this:
while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}
There are many other great tutorial out there like these to list a few:
http://www.vogella.com/articles/MySQLJava/article.html
http://www.java-samples.com/showtutorial.php?tutorialid=9
As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself
References:
http://zetcode.com/databases/mysqljavatutorial/
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
Easy Java method to get data from MySQL table:
/*
* CREDIT : WWW.CODENIRVANA.IN
*/
String Data(String query){
String get=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
get = rs.getString("");
}
}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
return get;
}
Here is what I just did right now:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.javafx.runtime.VersionInfo;
public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();
public static void main(String args[]) {
getData();
}
public static void getData () {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage",
"root", "root");
// here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
System.out.println("stmt " + stmt);
ResultSet rs = stmt.executeQuery("select * from carsData");
System.out.println("rs " + rs);
int count = 1;
while (rs.next()) {
String vehicleType = rs.getString("VHCL_TYPE");
System.out.println(count +": " + vehicleType);
count++;
}
con.close();
} catch (Exception e) {
Logger lgr = Logger.getLogger(VersionInfo.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
System.out.println(e.getMessage());
}
}
}
The Above code will get you the first column of the table you have.
This is the table which you might need to create in your MySQL database
CREATE TABLE
carsData
(
VHCL_TYPE CHARACTER(10) NOT NULL,
);
First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].
Add the Jar file to your workspace [build path].
Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.
Define the database name, userName, and Password for your connection.
Use the resultSet to get the data based one the column name from your database table.
Sample code is here:
public class JdbcMySQLExample{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
String user = "root";
String password = "root";
String query = "SELECT * from YOUR_TABLE_NAME";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println(ex);
}
}

Categories

Resources