How to retrieve all the name from MySQL? - java

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

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();
}
}
}
}

MySQL exception com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure [duplicate]

This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 6 years ago.
`
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
PreparedStatement pst = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
String query1 = "SELECT Name FROM Employee WHERE Name=?";
pst = conn1.prepareStatement(query1);
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String name = "";
int count = 0;
while(rs.next()){
title = rs.getString("name");
pst.setString(1, title);
rs1 = pst.executeQuery();
while(rs1.next()){
count++;
if(count % 100 == 0)
System.out.println(count);
}
}
System.out.println(count);
}
}
`
I am selecting value from the very large database based on some value from other database . I am running my select query in a while loop. After running my java code after getting many result , i am getting
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Communications link failure exception.
I have no idea why this is happening. If you guys have any idea please help
I already read the old questions based on this exception but none of them helps.
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
PreparedStatement pst = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String title = "",query1="";
StringBuffer newQuery = new StringBuffer("SELECT Name FROM Employee WHERE ");
int count = 0;
long nameCount = 0L;
while(rs.next()){
nameCount++;
title = rs.getString("name");
query1 = "Name=? or";
pst = conn1.prepareStatement(query1);
pst.setString(1, title);
newQuery.append(pst.toString().substring(pst.toString().indexOf('N'), pst.toString().length())+" ");
}
if ( nameCount > 0 ){
String Query = newQuery.toString().substring(0,newQuery.toString().length() - 3);
rs1 = conn1.createStatement().executeQuery(Query);
while(rs1.next()){
count++;
if(count % 50 == 0)
System.out.println(count);
}
}
}
}
Using PreparedStatement solves the problem of SQL Injection attack. Now the code is working.
I think this code is optimized, but it may have some syntax error:
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
//String query1 = "SELECT Name FROM Employee WHERE Name=?";
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String name = "";
StringBuffer newQuery = new StringBuffer("SELECT Name FROM Employee WHERE");
int count = 0;
long nameCount = 0L;
while(rs.next()){
nameCount++;
title = rs.getString("name");
newQuery.append(" Name='" + title + "' or");
}
if ( nameCount > 0 ){
newQuery = newQuery.subString( newQuery.length() - 3);
rs1 = conn1.createStatement.executeQuery( newQuery );
while(rs1.next()){
count++;
if(count % 100 == 0)
System.out.println(count);
}
}
}
}
Link failure may be because of so many query execution. Hence I have made it to fire only one or two queries, and you will get all your results.

How to dump resultset data into a database table

I am creating a resultset through an SQL query ('SELECT_PROCESS_INITIAL_REQUEST') which basically just grabs everything out of an SQL database table.
Statement stmt = conn.createStatement();
String sql = SQLDataAdaptor.SELECT_PROCESS_INITIAL_REQUEST;
ResultSet rsRequest = stmt.executeQuery(sql);
I then want to dump that data into an identical table to the original but in a different database. How would I do that?
Dumping it in another database means that Java will have to handle your resultset. So i'm afraid you have to do this programmatically.
Think of "prepared statements", "add batch method" and don't forget to execute your inserts every n records.
Using the example on Java Tutorial Website-
public static void viewTable(Connection con, String dbName)
throws SQLException {
//Modify this code according to 2nd database vendor and credentials-
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn2 = DriverManager.getConnection(url);
Statement stmt = null;
Statement insertStmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, " +
"SALES, TOTAL " +
"from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
insertStmt = conn2.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
String insertQuery = "INSERT INTO COFFEES (COF_NAME, SUP_ID, PRICE, sales, total) VALUES (coffeeName,supplierID, proce, sales, total);
try{
insertStmt.execute(insertQuery);
}catch(SQLExeption e){
e.printStackTrace();
}
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { stmt.close();}
if(insertStmt != null) {insertStmt.close();}
}
}

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