In here i want to obtain data from the MySQL DB & run the play method.but it execute at once.i wanted to get row one information pass that in to the ply method & get the second row information & pass it to the play method so on.
please help me to resolve this.
thank u in advance.
public class Player {
static Play PL = new Play();
public static void main(String[] args) {
try {
Statement stmt = null;
// connect to database radio
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/radio", "root", "");
stmt=conn.createStatement();
String sql = "SELECT Link FROM split";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int numColumns = rs.getMetaData().getColumnCount();
for ( int i = 1 ; i <= numColumns ; i++ ) {
System.out.println(numColumns);
String SongLocation = rs.getString(i);
System.out.println(SongLocation);
PL.play(SongLocation);
System.out.println("playing song");
}
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
I think you are looping through columns by using
int numColumns = rs.getMetaData().getColumnCount();
for ( int i = 1 ; i <= numColumns ; i++ ) {
...
instead try using a while loop
while (rs.next()) {
...
and because you need the index, inlude a local variable int i, that you just increment after each while loop
Related
I want to get the data from the two dates in MySQL and display only the range, however even if it is blank it won't display anything. Moreover, even if I change the simple date format to MM/dd/yyyy the table only display one row and date even I have 2 rows in the database daated 07/14/2022
Here is my code
private void table_stocks(String date_from, String date_to) {
try {
int table;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, username, password);
if(date_from.equals("") || date_to.equals("")){
pst = con.prepareStatement("SELECT `sales_number`, `date`, `amount_due` FROM `dnk_database`.`sales`;");
}
else{
pst = con.prepareStatement("SELECT `sales_number`, `date`, `amount_due`, SUM(`amount_due`) AS `total_sales` FROM `dnk_database`.`sales` WHERE `date` BETWEEN ? AND ?;");
pst.setString(1, date_from);
pst.setString(2, date_to);
}
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsd = rs.getMetaData();
table = rsd.getColumnCount();
DefaultTableModel load = (DefaultTableModel)jTable_salesValue.getModel();
load.setRowCount(0);
while(rs.next()) {
Vector v2 = new Vector();
for(int i = 1; i <= table; i++){
v2.add(rs.getString("sales_number"));
v2.add(rs.getString("date"));
v2.add(rs.getString("amount_due"));
}
load.addRow(v2);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Add_Items.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(Add_Items.class.getName()).log(Level.SEVERE, null, ex);
}
}
Also, want to display the SUM of the amount_due column from my SQL to a textfield and I don't know where to place this code
if (rs.next()==true) {
String sum_total = rs.getString("total_sales");
jTextField_totalSales.setText(sum_total);
}
You can accumulate the sum to a variable before the while loop, I assume you are using integer data type, then inside the loop sum the value. After the while loop is done display in the text field
int sumTotal = 0;
while(rs.next()) {
Vector v2 = new Vector();
for(int i = 1; i <= table; i++){
v2.add(rs.getString("sales_number"));
v2.add(rs.getString("date"));
v2.add(rs.getString("amount_due"));
sumTotal += rs.getString("amount_due") == null? 0 : Integer.parseInt(rs.getString("amount_due"));
}
load.addRow(v2);
jTextField_totalSales.setText(sumTotal);
}
I want to select multiple rows and return them in an Arraylist.
My Database structure looks like this:
1 Bestellnummer int(20)
2 BestellerID int(20)
3 ArtikelNummer int(20)
4 Anzahl int(10)
5 Preis double
It doesnt have a unique key, since it will not be changed.
I wrote this Method but i get the error:
" You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'BestellerID,ArtikelNummer,Preis FROM bestellungen WHERE
Bestellnummer = 1' at line 1Exception in thread "main"
java.lang.IndexOutOfBoundsException: Index 1 out-of-bounds for length
0"
public ArrayList<Bestellung> getBestellung (int i) throws SQLException {
ArrayList<Bestellung> Auftrag = new ArrayList<>();
final String SQL ="SELECT* BestellerID,ArtikelNummer,Preis FROM bestellungen WHERE Bestellnummer = ?" ;
ResultSet rs = null ;
try {
PreparedStatement stmt = con.prepareStatement(SQL,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt.setInt(1, i);
rs = stmt.executeQuery();
System.out.println("test");
while (rs.next()) {
Bestellung test = new Bestellung( i, rs.getInt("BestellerID"), rs.getInt("ArtikelNummer"), rs.getDouble("Preis"));
Auftrag.add(test);
}
}
catch (SQLException e) {
System.err.print(e);
}
finally {
if (rs!=null) {rs.close();
}
}
return Auftrag;
}
}
public class Bestellung {
private int Bestellnummer, BestellerID,ArtikelNummer,Anzahl;
private double Preis;
Here is the Class that Objects will be in the Arraylist:
Bestellung (int Bestellnummerin,int BestellerIDin,int ArtikelNummerin,double Preisin)
{
this.Bestellnummer = Bestellnummerin ;
this.BestellerID = BestellerIDin ;
this.ArtikelNummer = ArtikelNummerin;
this.Anzahl = 1;
this.Preis = Preisin;
}}
You can try this:
final String SQL ="SELECT BestellerID,ArtikelNummer,Preis
FROM bestellungen WHERE Bestellnummer = ?";
Edit: anything would help. If anyone can tell me the process at least I'd appreciate it.
I'm trying to get my code to read for an access database that I made. In that database are 2 tables, one is Soccer_Team and the other is Soccer_Players. I'm having an issue figuring out how to have the field name show up in front of the actual data. When I run the code now I get this:
Name: Location: Home Stadium: FC Barcelona Spain Camp Nou
Name: Location: Home Stadium: FC Bayern Munich Germany Allianz
I want the "Name:" to be followed by the club name, and so on... I am not familiar with Java so I am a little confused here.
Also, I want to print the second table from my database through an SQL query, that has it display the above but with the player information printed under each row... I don't even know where to begin doing that. I'm not sure I'm explaining this well, so sorry if I'm confusing people.
Sorry if this is asking too much but I am pretty lost... Thanks for any help guys.
package msjavaaccessdb;
import java.sql.*;
import java.util.*;
public class MSjavaAccessDB {
/** Creates a new instance of databaseApplication */
public MSjavaAccessDB() {
}
/**
* #param args the command line arguments
*/
static String nameOfJdbcOdbcDriver =
"sun.jdbc.odbc.JdbcOdbcDriver";
// static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String userName = "";
static String passwordForUser = "";
static Connection myConnectionRequest = null;
static Statement myStatementObject = null;
static ResultSet myResultTuples = null;
static ResultSetMetaData myResultTuplesMetaData = null;
static String queryToBeExecuted = "select * from Soccer_Team";
public static void main(String args[])
throws ClassNotFoundException {
try {
//Identify the driver to use
Class.forName(nameOfJdbcOdbcDriver);
//Attempt a connection to database...
Connection myConnectionRequest =
DriverManager.getConnection(
dataBaseNameDSN, userName, passwordForUser);
//Create a statement object, use its method to execute query
Statement myStatementObject =
myConnectionRequest.createStatement();
//Use statement object method to execute a query.
//Hold results in a resutl set...like a cursor
ResultSet myResultTuples = myStatementObject.executeQuery
(queryToBeExecuted);
//Call metadata to get the number of attributes
myResultTuplesMetaData = myResultTuples.getMetaData();
int numberOfAttributes =
myResultTuplesMetaData.getColumnCount();
System.out.println(Integer.toString(numberOfAttributes));
//For each row in result set, print ALL columns
for(int rowNum = 1; myResultTuples.next(); rowNum++) {
for (int i = 1; i <= numberOfAttributes; i++) {
if ( (i != 1) ) System.out.print (
myResultTuples.getString(i) + "\t");
else {//String xyz = myResultTuples.getString(1);
int xyz = Integer.parseInt( myResultTuples.getString(1));
System.out.print ("Name: ");
System.out.print ("Location: ");
System.out.print ("Home Stadium: ");
}
}
System.out.println("\n\n");
}
} // end of try block
//handle ALL exceptions to above database calls
catch (SQLException sqlError) {
System.out.println("Unexpected exception : " +
sqlError.toString() + ", sqlstate = " +
sqlError.getSQLState());
sqlError.printStackTrace();
}
} // end of main method of this class
} // end of the class
So I don't know how your datatable looks, but what i guess you want to do is print the column label and then the corresponding data value of the row.
for(int rowNum = 1; myResultTuples.next(); rowNum++) {
for (int i = 1; i <= numberOfAttributes; i++) {
//print column label
System.out.print(myResultTuplesMetaData.getColumnLabel(i) + ": ");
//print data value
System.out.print(myResultTuples.getString(i) + "\t");
}
System.out.println("\n\n");
//process SQl-Query about players and print out results in another for loop HERE
}
So for the second table you would have to do sth like SELECT * FROM table2 WHERE team IS (?) as a PreparedStatement and print out the results in another loop.
I can't get the error right now because I don't have access to NetBeans at this moment. I can update later when I am on my home computer. I'm not sure if what I did makes sense, because I don't exactly know what the rules of Java are... Hope this isn't stroke inducing.
package msjavaaccessdb;
import java.sql.*;
import java.util.*;
public class MSjavaAccessDB {
/** Creates a new instance of databaseApplication */
public MSjavaAccessDB() {
}
/**
* #param args the command line arguments
*/
static String nameOfJdbcOdbcDriver =
"sun.jdbc.odbc.JdbcOdbcDriver";
static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String dataBaseNameDSN = "jdbc:odbc:myDataSource";
static String userName = "";
static String passwordForUser = "";
static Connection myConnectionRequest = null;
static Statement myStatementObject = null;
static ResultSet myResultTuples = null;
static ResultSetMetaData myResultTuplesMetaData = null;
static ResultSet ResultTuples = null;
static ResultSetMetaData ResultTuplesMetaData = null;
static String queryToBeExecuted = "select * from Soccer_Team";
static string secondQuery = "select * from Soccer_Player where team is (?)";
public static void main(String args[])
throws ClassNotFoundException {
try {
//Identify the driver to use
Class.forName(nameOfJdbcOdbcDriver);
//Attempt a connection to database...
Connection myConnectionRequest =
DriverManager.getConnection(
dataBaseNameDSN, userName, passwordForUser);
//Create a statement object, use its method to execute query
Statement myStatementObject =
myConnectionRequest.createStatement();
//Use statement object method to execute a query.
//Hold results in a resutl set...like a cursor
ResultSet myResultTuples = myStatementObject.executeQuery
(queryToBeExecuted);
ResultSet ResultTuples = myStatementObject.executeQuery
(secondQuery);
//Call metadata to get the number of attributes
myResultTuplesMetaData = myResultTuples.getMetaData();
int numberOfAttributes =
myResultTuplesMetaData.getColumnCount();
System.out.println(Integer.toString(numberOfAttributes));
ResultTuplesMetaData = ResultTuples.getMetaData();
int numOfAttributes =
ResultTuplesMetaData.getColumnCount();
System.out.println(Integer.toString(numOfAttributes));
//For each row in result set, print ALL columns
for(int rowNum = 1; myResultTuples.next(); rowNum++) {
for (int i = 1; i <= numberOfAttributes; i++) {
//print column label
System.out.print(myResultTuplesMetaData.getColumnLabel(i) + ": ");
//print data value
System.out.print(myResultTuples.getString(i) + "\t");
}
System.out.println("\n\n");
}
for(int rowNum = 1; ResultTuples.next(); rowNum++) {
for (int i = 1; i <= numOfAttributes; i++) {
//print column label
System.out.print(ResultTuplesMetaData.getColumnLabel(i) + ": ");
//print data value
System.out.print(ResultTuples.getString(i) + "\t");
}
System.out.println("\n\n");
}
} // end of try block
//handle ALL exceptions to above database calls
catch (SQLException sqlError) {
System.out.println("Unexpected exception : " +
sqlError.toString() + ", sqlstate = " +
sqlError.getSQLState());
sqlError.printStackTrace();
}
} // end of main method of this class
} // end of the class
public void search() throws Exception{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:******";
String user = "*****";
String pass = "*****";
Connection con = DriverManager.getConnection(url, user, pass);
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows = new Vector();
for (int i=1; i<columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
for (int j=1; j<columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
tblPatient.setModel(dtm);
}
On my ResultSet rs = state.executeQuery() I used this SQL
"SELECT "
+ "pIDNo AS 'Patient ID',"
+ "pLName AS 'Last Name',"
+ "pFName AS 'First Name',"
+ "pMI AS 'M.I.',"
+ "pSex AS 'Sex',"
+ "pStatus AS 'Status',"
+ "pTelNo AS 'Contact No.',"
+ "pDocID AS 'Doctor ID',"
+ "pAddr AS 'St. No.',"
+ "pStreet AS 'St. Name',"
+ "pBarangay AS 'Barangay',"
+ "pCity AS 'City',"
+ " pProvince AS 'Province',"
+ " pLNameKIN AS 'Last Name',"
+ "pFNameKIN AS 'First Name',"
+ "pMIKIN AS 'M.I.',"
+ "pRelationKIN AS 'Relation',"
+ "pTotalDue AS 'Total Due'"
+ " FROM dbo.Patients");
First I run this line (pTotalDue didn't come up to jTable.)
And on my second attempt to display it I do this:
"SELECT pTotalDue AS 'Total Due' FROM dbo.Patients"
Now I tried this one, and I think something's really wrong about my codes. BTW this column has MONEY DATA TYPE
why does it didn't show to my JTable? could anyone tell me what is the problem with my codes?
(Problem in the answer that has given to me)
public class QueryOnWorkerThread extends SwingWorker{
private final JTable tableToUpdate;
public QueryOnWorkerThread( JTable aTableToUpdate ) {
tableToUpdate = aTableToUpdate;
}
#Override
protected TableModel doInBackground() throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:OJT_dsn";
String user = "sa";
String pass = "";
Connection con = DriverManager.getConnection( url, user, pass );
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows;
//note the <= check iso the < check (as the count starts at index 1)
for (int i=1; i<=columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
//note the <= check iso the < check (as the count starts at index 1)
for (int j=1; j<=columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
return dtm;
}
`#Override <<<<<<<<<<<<<<<<<<<<< I have a problem here it says : done() in javaapplication25.SearchPatient.QueryWorkerThread cannot override done() in javax.swing.SwingWorker overriden method does not throw java.lang.Exception , what does it mean sir?`
protected void done() throws Exception{
//this method runs on the EDT, so it is safe to update our table here
try {
tableToUpdate.setModel( get() );
} catch ( InterruptedException e ) {
throw new RuntimeException( e );
} catch ( ExecutionException e ) {
throw new RuntimeException( e );
}
}
try this
DefaultTableModel dtm=(DefaultTableModel)table.getModel();
for (int i = dtm.getRowCount() - 1; i > -1; i--) {
dtm.removeRow(i);
}
Connection con = DriverManager.getConnection(url, user, pass);
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("Your SQL Query");
while(rs.next())
{
String str1=rs.getString(1);
String str2=rs.getString(2);
String str3=rs.getString(3);
String str4=rs.getString(4);
String str5=rs.getString(5);
:
:
:
dtm.addRow(new Object[]{str1,str2,str3,str4,str5});
}
In you loops, your exit condition is
j<columns
this means thant the last column will never be recovered. try this insted:
for (int j=1; j<=columns; j++)
The fact that your last column does not appear is probably related to your loop statements, as already indicated by #Joan.
There are however more issues with this code. You should only update Swing components on the Event Dispatch Thread, and on that Thread you should not perform long running operations. In short, mixing SQL queries and updates of the JTable should not happen on the same thread. Consult the Concurrency in Swing guide for more info.
Using a SwingWorker could solve this issue:
public class QueryOnWorkerThread extends SwingWorker<TableModel, Void>{
private final JTable tableToUpdate;
public QueryOnWorkerThread( JTable aTableToUpdate ) {
tableToUpdate = aTableToUpdate;
}
#Override
protected TableModel doInBackground() throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:******";
String user = "*****";
String pass = "*****";
Connection con = DriverManager.getConnection( url, user, pass );
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows;
//note the <= check iso the < check (as the count starts at index 1)
for (int i=1; i<=columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
//note the <= check iso the < check (as the count starts at index 1)
for (int j=1; j<=columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
return dtm;
}
#Override
protected void done() {
//this method runs on the EDT, so it is safe to update our table here
try {
tableToUpdate.setModel( get() );
} catch ( InterruptedException e ) {
throw new RuntimeException( e );
} catch ( ExecutionException e ) {
throw new RuntimeException( e );
}
}
}
The SwingWorker can be started by calling
QueryOnWorkerThread worker = new QueryOnWorkerThread( tblPatient );
worker.execute();
Note how I changed the loops in your code
Try getting that column via ResultSet.getBigDecimal() rather than via ResultSet.getString(). Then put your retrieved BigDecimal.toPlainString() into your table cell.
Example:
data_rows.addElement(rs.getBigDecimal("pTotalDue").toPlainString());//Assuming your select returns a pTotalDue Column (e.g. SELECT pTotalDue,... FROM ...)
Try to Use an TableCellRenderer.
Implement the Renderer and render the Column with the Money Type in the form you wish.
Regards,
HL
I am trying update a large set of rows (around 5M). I first came across the heap overflow issue of having so many rows fetched in a resultset. Since I don't want to raise my heap size on this machine I was wondering if there is an effective way of doing this.
I tried setting the setFetchSize(Integer.MIN_VALUE) but then when I call the update function I get this error:
Streaming result set com.mysql.jdbc.RowDataDynamic#2087c268 is still active. No statements may be issued when any streaming result sets are open and in use on a given connection. Ensure that you have called .close() on any active streaming result sets before attempting more queries.
If I call close() on the result set I cannot update it of course. Here is my code
public void getRows()
{
Statement stmt = null;
ResultSet rs = null;
int countSpecialChars = 0;
int upper = 0, lower = 0, digits =0;
String pass = null;
int id = 0;
char thisChar;
String query = "select id,pass from datatable";
try {
this.conn.setAutoCommit(false);
stmt = this.conn.createStatement();
stmt.setFetchSize(Integer.MIN_VALUE);
rs = stmt.executeQuery(query);
while (rs.next()) {
pass = rs.getString(2).trim();
id = rs.getInt(1);
for (int i=0; i<=pass.length()-1; i++)
{
thisChar= pass.charAt(i);
if (thisChar >= 65 && thisChar <= 90) {
upper++;
} else if (thisChar >= 97 && thisChar <= 122) {
lower++;
} else if( thisChar >= 48 && thisChar <= 57) {
digits++;
}
else
{countSpecialChars++;}
}
Entropy entropy = new Entropy();
double naiveEntropy = entropy.naiveEntropy(pass);
NumberFormat formatter = new DecimalFormat("#0.00");
this.updateRow(id, pass.length(), digits, upper, lower, countSpecialChars, Double.parseDouble(formatter.format(naiveEntropy)));
countSpecialChars = 0;
upper=digits=0;
lower = 0;
}
rs.close();
}
catch (SQLException e)
...
}
public void updateRow(int id, int length, int numbers, int upper,
int lower, int specialChars, double naiveEntropy )
{
PreparedStatement updatePassEntry = null;
String updateString = "update cwlCompatiblePassUnique " +
"set length = ?, numbers = ?, upper = ?, lower = ?, specialChars = ?, ShannonEntropy = ? where id = ?";
try {
this.conn.setAutoCommit(false);
updatePassEntry = this.conn.prepareStatement(updateString);
updatePassEntry.setInt(1, length);
...
updatePassEntry.setInt(7, id);
updatePassEntry.executeUpdate();
this.conn.commit();
}
catch (SQLException e)
...
}
Any ideas on what can be done?
Thanks
you call updateRow() method inside the rs.next() loop; which tries to make a SQL update on a SQL field (id) that is currently being processed inside your while (rs.next()) loop. this will raise the error you get. i suggest you write a method for pulling rs and storing them in java objects vector as a first step. this method will close the rs after exiting. then write another method to do both processing and update data on your cached vector objects .
something like this:
private void Vector<DataSet> getDataSet(){
Vector<DataSet> data=new Vector<DataSet>();
String query = "select id,pass from datatable";
try {
this.conn.setAutoCommit(false);
stmt = this.conn.createStatement();
stmt.setFetchSize(Integer.MIN_VALUE);
rs = stmt.executeQuery(query);
while (rs.next()) {
pass = rs.getString(2).trim();
id = rs.getInt(1);
data.addElement(new DataSet(id,pass));
}
}catch(Exception e){
// here close connection and rs
}
}
private void udpateData(Vector<dataSet> data){
//process data and update her
}
static class DataSet{
int id;
String pass;
//constructor here
}
Connection object should not hold multiple resultset object at a time.
After creation of ResultSet and Statement Objects, each has to close explicitly like,
resultSet.close()
statement.close()