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();
}
}
Related
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
Hello I want to populate a table from database but I have some difficult to do since I am newbie in java programming
here is the Users.java where the method getData(select) is implemented:
#Override
public Users getData(Users u) throws Exception {
Connection con = null;
Users user = null;
ResultSet rs = null;
PreparedStatement ps = null;
try{
con = getConnection();
String sql = "SELECT * FROM USERS";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
user = new Users();
user.setFirstName(rs.getString("First_NAME"));
user.setLastName(rs.getString("LAST_NAME"));
user.setAge(rs.getInt("AGE"));
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}finally{
rs.close();
ps.close();
closeConnection(con);
}
return user;
}
Well the data is stored in Users object now and I want to display it on a jTable which is located in patientJframe file can you tell me how to do that?
I created a method on patientJframe but I dont know what to do Im stuck onhere.
PatientJframe :
public void PopulatejTable(){
try {
Users u = null;
Users user = UsersDB.getInstance().getData(u);
if(user== null){
DefaultTableModel dtm = (DefaultTableModel)jTable.getModel();
dtm.setRowCount(0);
Vector vector = new Vector();
vector.add(user.getCin());
vector.add(user.getLastName());
vector.add(user.getFirstName());
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
The method it is correct ? please can you help me ?
I have a jComboBox that getting data from MySQL server database.
When I add new data to database, the jComboBox doesn't show it, and I must reopen my program to add the new data to jComboBox.
How can I refresh jComboBox data automatically?
This is my code :
private void dataComboBox(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select id from perfume order by id asc";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0] = res.getString(1);
jComboBox5.addItem(ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void showCBdata(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select name from perfume where id='"+jComboBox5.getSelectedItem()+"'";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0]= res.getString(1);
jTextField8.setText((String) ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
//call method
private void jComboBox5ActionPerformed(java.awt.event.ActionEvent evt) {
showCBdata();
}
can you help me?
thank you..
You can do it in this way it will automatically refresh the combobox
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
removeAllItems(); method will clean the combobox to insure that not to repeat values.
You do not need to create a separate Object to add in jComboBox instead you can add String too.
Inzimam Tariq IT's Code (above):
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
I suggest putting all of this code inside an ActionListener. So that each time there the mouse is entered over the comboBox the above code will run. You should do the following:
public void mouseEntered(MouseEvent e) {
//the above code goes here
}
I suggest using a mouseListener:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
But if you want to look at other ActionListeners you can see them here:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Once you add a new registry in the DB, do a removeAllItems comboBox.removeAllItems(); and repopulate de combobox,
My example:
jComboLicorerias.removeAllItems();
try {
Conector = Conecta.getConexion();
Statement St = Conector.createStatement();
try (ResultSet Rs = St.executeQuery(Query)) {
while (Rs.next()) {
jComboLicorerias.addItem(Rs.getString("nombreLicoreria"));
}
St.close();
}
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error en la consulta.");
I'm using flex, Java and sql server for webmapping application and i'm trying to fill my combobox from database, but i just get results like this [Object Object] [Object Object] [Object Object] [Object Object] instead of getting the correct values of the fields, this is the code, i think all is right but it doesn't work !!! can you help be to find what i'm messing !!
so first this is the code of my class, it selects a column (Intitule Chapitre) from database
public class RapportDao {
public Connection conectar(){
Connection cn = null;
String connectionUrl = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=mabase;user=sa;password=sa;";
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
cn = DriverManager.getConnection(connectionUrl);
}
catch(Exception ex)
{
System.out.println("Error : " + ex.getMessage());
}
return cn;
}
public ArrayList<Rapport> Selection() {
Connection conn = conectar();
ArrayList<Rapport> list = null;
if (conn!=null){
try{
Rapport pr = null;
String a;
list = new ArrayList<Rapport>();
String sql = "select IntituleChap from Rapport";
Statement st = conn.createStatement();
ResultSet rs=st.executeQuery(sql);
while (rs.next())
{
a=rs.getString("IntituleChap");
pr = new Rapport();
pr.setIntituleChap(a);
list.add(pr);
}
}
catch(SQLException e ) {
// System.out.print(e.getMessage());
System.out.println("Error = " + e.getMessage());
}
}else
{
}
return list;
}
}
and this is my actionscript code for combobox
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:esri="http://www.esri.com/2008/ags"
minWidth="1000" minHeight="700" applicationComplete="application1_applicationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import spark.components.ComboBox;
private function getTypeprojetResult(event : ResultEvent):void
{
//Alert.show(""+event.result);
}
protected function application1_applicationCompleteHandler(event:FlexEvent):void
{
RemoteRapportDao.Selection()
}
]]>
<fx:Declarations>
<s:RemoteObject id="RemoteRapportDao"
destination="RapportDaoDest"
fault="onFault(event)">
<s:method name="Selection" result="getTypeprojetResult(event);"/>
</s:RemoteObject>
</fx:Declarations>
<s:ComboBox id="cmb" x="10" y="13" width="162" labelField="IntituleChap" dataProvider="{RemoteRapportDao.Selection.lastResult}" />
RemoteRapportDao : is the id RemoteObject
Selection() : my method on the service
any one could help me ?
It's very likely to having issue with representing the results from the query correctly, and therefore the labelField is not trigered correctly with the combo box object.
I would suggest to create a data model representing the results, which would not only great improve readability of the code, but will help you aswell with such no-go issues.
possible example of a data model ( just for a testing purposes ).
package myTopLevelPackage.myPackage
{
public class ComboBoxItemDataModel
{
public var intituleChap: String;
public function ComboBoxItemDataModel( o : Object )
{
super();
this.intituleChap = o[ 'IntituleChap' ];
trace( JSON.encode( o ) );
// use this or other suitable method to see actually how Your object looks like, in order to set the object property correctly in the assignment above.
}
}
}
Please note that I have switched using capital character for a variable IntituleChap to intituleChap.
it works, thank you all for your help, i just should use ArrayCollection instead of arraylist.
public ArrayCollection Selection() {
Connection conn = conectar();
ArrayCollection list = new ArrayCollection();
if (conn!=null){
try{
Rapport pr = null;
String a;
list = new ArrayList<Rapport>();
String sql = "select IntituleChap from Rapport";
Statement st = conn.createStatement();
ResultSet rs=st.executeQuery(sql);
while (rs.next())
{
a=rs.getString("IntituleChap");
pr = new Rapport();
pr.setIntituleChap(a);
list.add(pr);
}
}
catch(SQLException e ) {
// System.out.print(e.getMessage());
System.out.println("Error = " + e.getMessage());
}
}else
{
}
return list;
}
thank you all :)
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)