Java: how to print the rows from database? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this program:
class DataRetrieve {
DataRetrieve() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/phonebook", "root", "1234");
Statement st = con.createStatement();
st.executeQuery("select * from contacts");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public class MainProgram {
public static void main(String[] args) {
DataRetrieve dr = new DataRetrieve();
//here i want to print that table rows into Console using this
System.out.println(); // How do you print here that table rows?
}
}
Can anyone explain how to print this database information in System.out.println?

You can create a ResultSet.
ResultSet rs = st.executeQuery("select * from contacts");
Then you can iterate over ResultSet, and get the rows.
while (rs.next()) {
System.out.println(rs.getString(1)); //gets the first column's rows.
}
To get all the column's datas:
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for(int i = 1; i < columnsNumber; i++)
System.out.print(rs.getString(i) + " ");
System.out.println();
}
If you want to print the database information from MainProgram calls, you can return the ResultSet and iterate over it in your main method.
In this case you should create a method in MainProgram.
class DataRetrieve {
DataRetrieve() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/phonebook", "root", "1234");
Statement st = con.createStatement();
rs = st.executeQuery("select * from contacts");
}
catch(Exception e) {
e.printStackTrace();
}
}
public ResultSet getResultSet() {
return rs;
}
private ResultSet rs = null;
}
And in your main method:
public static void main(String[] args) {
DataRetrieve dr = new DataRetrieve();
//here i want to print that table rows into Console using this
System.out.println(); // How do you print here that table rows?
ResultSet rs = dr.getResultSet();
while (rs.next()) {
System.out.println(rs.getString(1)); //gets the first column's rows.
}
}

Use the following code:
class DataRetrieve {
DataRetrieve() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/phonebook", "root", "1234");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from contacts");
System.out.println(rs.getInt(1));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public class MainProgram {
public static void main(String[] args) {
DataRetrieve dr = new DataRetrieve();
//here i want to print that table rows into Console using this
System.out.println(); // How do you print here that table rows ?
}
}
Well I have caught the rows returned from database in ResultSet instance. You can use getInt(xxx), getString(xxx) and etc to get the related values and then to print them.

One basic fault you did is opened the connection but never closed it. Its not a good practice you should always close it for releasing the resources.
In your code first st.executeQuery("select * from contacts"); will return a ResultSet object what you need to do is just iterate the ResultSet and get the rows.
DataRetrieve() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("yourUrl", "userName", "password");
Statement st = con.createStatement();
ResultSet resultSet = st.executeQuery("select * from contacts");
while(resultSet.next())
{
String columnName1= rs.getString("nameOfColumn1");
int columnName2= rs.getInt("nameOfColumn2");
float columnName3= rs.getFloat("nameOfColumn3");
System.out.println(columnName1+"\t"+ columnName2+"\t"+ columnName3);
}
}
}
catch(SQLException e) {
e.printStackTrace();
}
finally{
//dont forget the closing statements
}

Related

SQLServerResultSet:1 output instead of the data

I want my function to return the result of the Select statement, but in instead it prints SQLServerResultSet:1. How do I do to print/return the data in my function?
My function should execute the SQL statement and store the result in a variable.
public ResultSet selectSubmissions(int department) {
Connection connection = Database.getConnection();
String sql = "SELECT * FROM [MyDB_Widget].[dbo].[surveys] INNER JOIN [MyDB_Widget].[dbo].[instructors] ON surveys.instructor_id = instructors.instructor_id Where instructors.department_id = 2;";
ResultSet rs = null;
try {
Statement statement = connection.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
rs.getString(1); //or rs.getString("column name");
}
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
return rs;
}

Type Mismatch : cannot convert from Int to ResultSet using oracle sql developer. ExecuteUpdate

I can't add items to the database because of this apparently.
Not putting the entire code, hope you can understand.
import java.sql.Connection/Driver/ResultSet/SQLException/Statement;
public class Main {
public static void main(String[] args) {
Statement st = null;
ResultSet rs = null;
try(Connection conn = everything right here)){
if(conn != null) {
System.out.println("Success conn!");
String query = "INSERT INTO students (id, nome) VALUES (1, 'College Name')";
st = conn.createStatement();
rs = st.executeUpdate(query);
Giving me type mismatch: can't resolve int to ResultSet in
rs = st.executeUpdate(query);
// continuation of above code
while(rs.next()) {
System.out.println("\nRegistro");
System.out.println("id: " + rs.getInt(1));
System.out.println("nome: " + rs.getString(2));
}
rs.close();
st.close();
conn.close();
}
}
}
}

importing last row of mysql database in all rows of jtable (Java Swing)

I'm trying to import all of the data from mysql database into a jtable using arraylists but something isn't working right, as i get the number of rows right but they're all values of the last row
Here's the code
public ArrayList<medicaments> medicaments_list() {
ArrayList<medicaments> medicament_lists = new ArrayList<medicaments>();
String select_nom_type_med = "select * from medicaments where login=?";
PreparedStatement stmt;
ResultSet rs2;
medicaments med;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
stmt = con.prepareStatement(select_nom_type_med);
stmt.setString(1, Utilisateur.getLogin());
rs2 = stmt.executeQuery();
while (rs2.next()) {
emptytable = false;
med = new medicaments(rs2.getInt("med_id"), rs2.getString("login"), rs2.getString("med_nom"), rs2.getString("med_type"), rs2.getString("date_debut"), rs2.getString("date_fin"), rs2.getString("frequence"), rs2.getString("temps_1"), rs2.getString("temps_2"), rs2.getString("temps_3"), rs2.getString("temps_4"), rs2.getString("temps_5"), rs2.getString("Stock"), rs2.getString("rappel_stock"));
medicament_lists.add(med);
}
} catch (ClassNotFoundException e1) {
System.out.println(e1);
} catch (SQLException e1) {
System.out.println(e1);
}
return medicament_lists;
}
public void populate_jTable_from_db() {
ArrayList<medicaments> dataarray = medicaments_list();
model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(dataarray.size());
int row = 0;
for (medicaments data : dataarray) {
model.setValueAt(data.get_nom_med(), row, 0);
model.setValueAt(data.get_type_med(), row, 1);
row++;
}
jTable1.setModel(model);
}
and here's the result :(there's 3 rows in my database and po is the last one i added)
Make sure your recordset actually contains something and it's what you really want:
while (rs2.next()) {
if (rs2.getString("login").equals(Utilisateur.getLogin())) {
emptytable = false;
med = new medicaments(rs2.getInt("med_id"), rs2.getString("login"),
rs2.getString("med_nom"), rs2.getString("med_type"),
rs2.getString("date_debut"), rs2.getString("date_fin"),
rs2.getString("frequence"), rs2.getString("temps_1"),
rs2.getString("temps_2"), rs2.getString("temps_3"),
rs2.getString("temps_4"), rs2.getString("temps_5"),
rs2.getString("Stock"), rs2.getString("rappel_stock"));
medicament_lists.add(med);
}
}

How to retrieve all the name from MySQL?

I want to retrieve all the name and the number of row from MySQL to java. So far I only able to retrieve the total row number but I only get the last name. What's wrong here ?
StaffManagement.java
adminAPI api= new adminAPI();
try {
int num= api.displayCheckBoxAndLabel();
String allName= api.displayName();
System.out.println(num+allName);
}
adminAPI
public int displayCheckBoxAndLabel() throws Exception // get the number of row
{
int count = 0;
String sql="Select count(*) AS adminID from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
count= rs.getInt("adminID");
}
ps.close();
rs.close();
conn.close();
return count ;
}
public String displayName() throws Exception // get all the name
{
String name = null;
String sql="Select name from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
name= rs.getString("name");
}
ps.close();
rs.close();
conn.close();
return name ;
}
You currently return a single String, and your method iterates all of the admin names (but terminates after the final row, so that's your result). Instead, build a List of names and return that. You could also use a try-with-resources close to close your Connection, Statement and ResultSet instances. Something like
public List<String> displayName() throws Exception // get all the name
{
String sql = "Select name from admin";
List<String> names = new ArrayList<>();
DatabaseConnection db = new DatabaseConnection();
try (Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString("name"));
}
}
return names;
}
This might be helpful
private String names[];
int i = 0;
while (rs.next()) {
names[i] = rs.getString("name");
i++;
}
Then you can use a for loop to return each name in StaffManagement.java

How to Store Array value in table column in mySql using java

hello i am trying to retrieve data in two result set. then i have store in both resultset to String Array, after this process i have to store my String array to another table how to so this kindly tell me..
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.
getConnection("jdbc:mysql://localhost:3306/lportal", "root", "ubuntu123");
PreparedStatement stmt = (PreparedStatement) con.
prepareStatement("SELECT * FROM Testi_Testimonial where subject = ?");
stmt.setString(1, search);
stmt.execute();
rs = (ResultSet) stmt.getResultSet();
while (rs.next()) {
anArray[i] = rs.getString("subject");
System.out.println(anArray[i]);
i++;
count++;
}
PreparedStatement stmt1 = (PreparedStatement) con.
prepareStatement("SELECT * FROM Testi_Testimonial where subject != ?");
stmt1.setString(1, search);
stmt1.execute();
rs1 = (ResultSet) stmt1.getResultSet();
while (rs1.next()) {
anArray[i] = rs1.getString("subject");
System.out.println(anArray[i]);
i++;
count++;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("problem in connection");
}
Please tell me how should I store my array to Temp table? my "Temp" table has column subject I want to store myArray to subject column... kindly tell me how to do this.
try this after getting resultset in rs:
PreparedStatement st = (PreparedStatement) con.prepareStatement("insert into temp values(?)");
i=0;
while(rs.next())
{
st.setString(1,anArray[i]);
st.executeUpdate();
i++;
}
You just iterate the arrayList. You got the subject List as respective.
public class TestArrayList {
public static void main(String[] args) {
/*create two arrayList*/
List<String> tempOneList = new ArrayList<String>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay", "root", "root");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM subjecttable");
while (res.next()) {
tempOneList.add(res.getString("subject"));
}
ResultSet resOne = st.executeQuery("SELECT * FROM subjecttabletwo");
while (resOne.next()) {
tempOneList.add(resOne.getString("subject"));
}
System.out.println("temp/List>>--" + tempOneList.size());
for(int i=0;i<tempOneList.size();i++){
System.out.println(tempOneList.get(i));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("problem in connection");
}
}
}
PreparedStatement ps =
(PreparedStatement) con.prepareStatement("insert into temp values(?)");
j=0;
while(rs.next())
{
ps.setString(1,anArray[j]);
ps.executeUpdate();
j++;
}

Categories