Insert Array in Phpmyadmin database - java

I'm trying to insert a array in my database and I selected 3 values like broccoli,carrots,Cabbage but only broccoli is inserted ang those 2 values are not inserted can someone help me with this thank you.
Servlet
String[] vege = request.getParameterValues("vegetables-selected");
Model mod = new Model();
mod.setVegetables(vege);
Model
private String[] Vegetables;
public String[] getVegetables() {
return Vegetables;
}
public void setVegetables(String[] vegetables) {
Vegetables = vegetables;
}
Operation
[public static int AddRecipes(Model mod) {
int i = 0;
try {
Driver(dbloader);
Connection con = getConnection();
PreparedStatement pst = con.prepareStatement(Add_Recipe);
pst.setInt(1, mod.getUsers_ID());
pst.setString(2, mod.getTitle());
pst.setString(3, mod.getVegetables());
i = pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return i;
}
Click this for photo

Related

Using two combobox to set conditions for a search in a database and displaying in jtable

I need to display the details of students in a particular stream of a schoolclass in Jtable from a database containing all the names of students in the school. I have two jComboboxes, on to select which class and the other to select the stream. I am asking for a way to define these two conditions in order to display all the students in a particular stream in a jtable. I apologize in advance if my code is messy.
public Classes() {
initComponents();
show_student();
}
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return con;
}
public ArrayList<Individualclass> studentList(String ValToSearch) {
ArrayList<Individualclass> list = new
ArrayList<Individualclass>();
Statement st;
ResultSet rs;
try {
Connection con=getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM `students` WHERE CONCAT(`firstName`, `surname`, `otherNames`, `regNo`) LIKE '%"+ValToSearch+"%'";
rs = st.executeQuery("searchQuery ");
Individualclass ic;
while(rs.next()) {
ic = new Individualclass(
rs.getString("firstName"),
rs.getString("surname"),
rs.getString("otherNames"),
rs.getInt("regNo")
);
list.add(ic);
}
} catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return list;
}
public void findStudents() {
}
private void sClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sClassActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where sClass=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String) sClass.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_sClassActionPerformed
private void streamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_streamActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where stream=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String)stream.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_streamActionPerformed
public void show_student() {
ArrayList<Individualclass> list = new ArrayList<Individualclass>();
DefaultTableModel model = (DefaultTableModel)jTable_Display_Student.getModel();
Object [] row = new Object[13];
for(int i = 0; i < list.size(); i++) {
row[0] = list.get(i).getFirstName();
row[1] = list.get(i).getsurname();
row[2] = list.get(i).getOtherNames();
row[3] = list.get(i).getregNo();
model.addRow(row);
}
}

radio button show values in combo box

I confused with this if-else because I'm new in Java & MySQL and I tried to make it by myself.
public Menu() {
initComponents();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restaurant", "root", "");
System.out.println("ODBC Connection Successful");
showCategory();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("ODBC Connection Failed" + e);
}
}
if - else
private void showCategory() {
try {
Statement stmt;
stmt = con.createStatement();
if (rbMFood.isSelected()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY02'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
} else {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY01'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Radio Button
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Food";
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Drink";
}
And I declare the function in the end of the program
private String type;
When I click drink / food, the category still drink's category.
The database
Any help would be greatly appreciated!
You are using rs.getString("menu_cat") But the format is rs.getString(<Column Name>) But you are using rs.getString(<Table Name>) As "menu_cat" is name of the table and not the name of the column.
AFTER POSTING CONSTRUCTOR
What I see from the code you have posted, is that You have called showCategory() in the constructor. This method is responsible for populating the JComboBox cmbMCat. Now the cmbMCat is being populated when you are creating the new Menu. After that the items list of the cmbMCat does not change.
So, What I suggest is that you call the showCategory() from the rbMFoodActionPerformed and rbMDrinkActionPerformed methods. I hope this will solve your problem.
Also add cmbMCat.removeAllItems() before Statement stmt; to remove all the items that are there in the cmbMCat and reset it with a fresh list of items.
After comment regarding the if-else
Change the showCatagory() as below:
private void showCategory() {
cmbMCat.removeAllItems();
try {
PreparedStatement stmt; //Used Prepared statement
String sql = "SELECT * FROM menu_cat WHERE type_id = ?";
stmt = con.prepareStatement(sql);
if (type.equals("Drink")) {
stmt.setString("TY01");
} else {
stmt.setString("TY02");
}
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Also note that you eventListener code should be:
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt){
type = "Food";
showCategory();
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt){
type = "Drink";
showCategory();
}

Jtable values duplicating the last value

Im developing java desktop application for my college assignment. I have encounter a problem while i'm loading values to the Jtable. I used following code to load values. It makes duplicate entries. Can you please help me to get rid of this issue?
private void LoadSupplierTable() {
clearTable((javax.swing.table.DefaultTableModel) tblSupp.getModel());
javax.swing.table.DefaultTableModel dtSupp = (javax.swing.table.DefaultTableModel) tblSupp.getModel();
Vector ver = new Vector();
try {
ResultSet resO = null;
String sqo = "select id,name from supplier";
Connection coo = DataBaseConnection.getDbConnection();
PreparedStatement pso = coo.prepareStatement(sqo);
resO = pso.executeQuery();
while (resO.next()) {
ver.add(resO.getInt("id"));
ver.add(resO.getString("name"));
dtSupp.addRow(ver);
}
} catch (Exception e) {
e.printStackTrace();
}
}
You should declare the vector inside the while loop... just copy paste the following code
private void LoadSupplierTable() {
clearTable((javax.swing.table.DefaultTableModel) tblSupp.getModel());
javax.swing.table.DefaultTableModel dtSupp = (javax.swing.table.DefaultTableModel) tblSupp.getModel();
try {
ResultSet resO = null;
String sqo = "select id,name from supplier";
Connection coo = DataBaseConnection.getDbConnection();
PreparedStatement pso = coo.prepareStatement(sqo);
resO = pso.executeQuery();
while (resO.next()) {
Vector ver = new Vector();
ver.add(resO.getInt("id"));
ver.add(resO.getString("name"));
dtSupp.addRow(ver);
}
} catch (Exception e) {
e.printStackTrace();
}
}

How to get value at particular index from a vector?

When I return vector data using elementAt(2), I am getting this output.
Hello [162, Experiment 3.doc, E:\Desktop\Experiment 3.doc, doc, 35.5 kb]
I want the index value: "Experiment 3.doc".
// Function to fetch data from Database and store in jtable
public Vector getEmployee(String searchQuery)throws Exception
{
Connection con = null;
try{
Class.forName(driver);
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try{
Vector<Vector<String>> employeeVector = new Vector<>();
con = DriverManager.getConnection(url,"conjure","conjure");
String query = "SELECT * FROM APP.FILES WHERE NAME LIKE '%"+searchQuery+"%'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
Vector<String> file = new Vector<>();
file.add(rs.getString(1)); //Empid
file.add(rs.getString(2)); //name
file.add(rs.getString(3)); //position
file.add(rs.getString(4)); //externsion
file.add(rs.getString(5)); //size
employeeVector.add(file);
}
rs.close();
return employeeVector;
} catch (Throwable err) {
err.printStackTrace();
System.out.println("Inside two");
} finally {
con.close();
}
return null;
}
// Button click, show data in jtable.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
String searchQuery = jTextField1.getText();
//get data from database
DBEngine dbengine = new DBEngine();
try {
data = dbengine.getEmployee(searchQuery);
System.out.println("Hello "+data.elementAt(2));
jTable1.setModel(new DefaultTableModel(data,header));
} catch (Exception ex) {
ex.printStackTrace();
}
}
Now I want to use column 3, i.e. filename (Experiment 3.doc) somewhere else.
How can I do that?
You have a Vector of Vectors.
data.elementAt(2) will return a Vector of Strings. You then need to get the next element from this resulting Vector, presumably data.elementAt(2).getElementAt(2)

JTable display list of events under one date

I want to post a question about something I wish to do particularly but have no idea how to approach this as I am new with JTables.
This is what I have atm:
But I would like to arrange the table like this:
So that under a particular date, all events that correspond to that date are shown rather than individually like have above.
Here are the related classed in question, I am not sure where and how to make the alternations to allow me to achieve the above.
public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
for (int column=0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
Vector rows = new Vector();
while(rs.next()) {
Vector newRow = new Vector();
for (int i =1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows,columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public class EventModel {
public TableModel getTableData() {
TableModel model=null;
try {
String sql = "SELECT eventID as 'Event ID', date as 'Date',eventName as 'Name', time as 'Start Time' FROM Event";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
model = (DbUtils.resultSetToTableModel(rs));
}
catch(SQLException e){
e.printStackTrace();
}
finally {
try {rs.close(); pst.close();}
catch(SQLException e){} }
return model;
}
public Events getEvent(String tableClick) {
try {
pst = conn.prepareStatement("SELECT * FROM Event WHERE eventID='"+tableClick+"' ");
rs = pst.executeQuery();
while(rs.next()){
e.setEventName(rs.getString(2));
e.setEventDate(rs.getString(3));
e.setEventTime(rs.getString(4));
e.setEventVenue(rs.getString(5));
e.setEventDetail(rs.getString(6));
e.setEventOpportunity(rs.getString(7));
e.setEventMoreDetails(rs.getString(8));
e.setEndTime(rs.getString(9));
}
}
catch(SQLException ex){
ex.printStackTrace();
} finally {
try {
rs.close();
pst.close();
} catch (Exception e) {
}
}
return e;
} //end getEvent
}
public class EventController {
private KeyAdapter keyAdapter = new KeyAdapter() {
#Override
public void keyReleased(java.awt.event.KeyEvent e) {
if((e.getKeyCode()==KeyEvent.VK_UP) || (e.getKeyCode()==KeyEvent.VK_DOWN)) {
changeEvent();
}
}
};
public void changeEvent() {
int rowSelected = view.tableEvent.getSelectedRow();
tableClick = view.tableEvent.getModel().getValueAt(view.tableEvent.convertRowIndexToModel(rowSelected), 0).toString();
events = model.getEvent(tableClick); //tell model to change its state based on user input on views
view.changeDisplay(events);
}
}
public class EventView {
public void changeDisplay(Events e) {
evTitle.setText(""+e.getEventName());
evWhen.setText("When: "+ e.getEventDate());
evWhere.setText("Where: "+ e.getEventVenue());
evDescription.setText(""+ e.getEventDetail());
evOpportunity.setText(""+ e.getEventOpportunity());
evMoreDet.setText(""+ e.getEventMoreDetails());
endTime.setText("End Time: "+e.getEndTime());
}
}
e is the object of the class Events which is just a bean.
You may be able to simply setAutoCreateRowSorter(true). Addendum: Because Date implements Comaprable, ensure that your TableModel returns type Date.class for the date column, as shown here. See also How to Use Tables: Sorting and Filtering.
A more elaborate approach would be to use a tree-table such as Outline, shown here. The top level(s) would be dates, and the leaves would be events.

Categories