Sqlite Column Determination Error - java

I'm trying to get selection from J combo Box and use that to find table from the data base. But instead an error comes up:
My codes it:
JButton btnGo = new JButton("Go!");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Connection conni = null;
ResultSet rs=null;
PreparedStatement pst=null;
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String x = comboBox.getSelectedItem().toString();
String sql="select * from " + x;
pst=conni.prepareStatement(sql);
rs=pst.executeQuery();
while(rs.next()){
String name = rs.getString("Namet");
nameofguy.setText(rs.getString(name));
}
}catch(Exception i){
JOptionPane.showMessageDialog(null, i);
}
I'm searching for table.. but it says cannot find column.

Here's your problem
while(rs.next()){
String name = rs.getString("Namet");
//rs.getString returns Ayaan. So value of name is "Ayaan"
nameofguy.setText(rs.getString(name));
// Youre trying to get the value corresponding to the column Ayaan here
//This is why the exception is thrown as there is no column called Ayaan
}
Instead do
while(rs.next()){
String name = rs.getString("Namet");
nameofguy.setText(name);
}

Related

Java- check if dataset from table already exists

I select the datasets with a button from my database table, but every time I click on the button it loads the same datasets I already have:
public void actionPerformed(ActionEvent e) {
java.sql.Connection con;
try {
con = DriverManager.getConnection ("jdbc:mysql://localhost:3307/lessons","root","");
String query =" SELECT * FROM lessons";
PreparedStatement statement = con.prepareStatement(query);
ResultSet rs = statement.executeQuery(query);
while(rs.next())
{
int lesson = rs.getInt("lessons");
String name= rs.getString("names");
String number= rs.getString("numbers");
model.addRow(new Object[]{lessons, names, numbers});
table.setVisible(true);
}
I just want to print the datasets which are unique.
Thank you all in advance.
You have to remove all available rows before loading data to table
DefaultTableModel model = (DefaultTableModel)your_table.getModel();
...
model.setRowCount(0); // add this line
while(rs.next()) {
int lesson = rs.getInt("lessons");
String name= rs.getString("names");
String number= rs.getString("numbers");
....
model.addRow(new Object[]{lessons, names, numbers});
}

Retrieve maximum value from database and displays in JTextfield in java eclipse

I want to extract maximum value from database and displays in JTextfield in Java. I tried the code shown below. But I get error _No such column 'Enquiry No'.
But 'Enquiry No' colum name is available in enquiry table
Enquiry No is column name
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
try {
String query = "Select max(`Enquiry No`) from enquiry ";
PreparedStatement pst = conn.prepareStatement(query);
// pst.setString(1,textField.getText());
ResultSet rs = pst.executeQuery();
while (rs.next()) {
textField.setText(rs.getString("Enquiry No"));
}
} catch (Exception f) {
f.printStackTrace();
}
}
}
To get max or min, avg, count or any aggregate functions you have to :
put your result as a value and get it like this :
String query="Select max(`Enquiry No`) as max from enquiry ";
...
textField.setText(rs.getString("max"));
Or get the first result like this :
String query="Select max(`Enquiry No`) from enquiry ";
...
textField.setText(rs.getString(1););

Java TableModel duplicating rows - How do I stop this from happening?

So in application I've created a search for name page where the user will enter there the name and as the user types ( Every time a key is pressed) an SQL statement is ran that will get the records like 'name%'.
This works fine but when it comes to putting the values into the table everytime the user presses a key it append the found results to the table instead of replace the values. Meaning everytime a key is pressed...duplicate rows are generated.
So I was wondering if anyone had a solution to stop the rows being duplicated and instead replaced with the new values? Im using a default table model:
private DefaultTableModel tModel = new DefaultTableModel(0, 0);
My code:
#Override
public void keyReleased(KeyEvent e) {
updateTable();
table.setModel(tModel);
formPanel.add(table);
tModel.fireTableDataChanged();
}
public void updateTable(){
System.out.println("Save member 1");
try{
//CHANGE THE VALUES SO WHEN CLICKS SAVE MEM
/*-------------------------------------*/
//Connection + Statement
conDB = getConnection();
stmt = conDB.createStatement();
String searchSql = "select * from members where name "
+ " LIKE '" + txtName.getText() +"%'";
if(!txtName.getText().equals(""))
{
r = stmt.executeQuery(searchSql);
}
System.out.println("searching");
tModel.setColumnIdentifiers(columnNames);
while(r.next()){
tModel.addRow(new Object[] {
r.getString("name")
});
}
}
catch(SQLException er){
System.out.println("Error was: " + er);
}
}
public searchBoth(){
super("Search");
this.setBounds(400, 500, 854,400);
this.setVisible(true);
mainCon.add(formPanel);
formPanel.add(lblName);
formPanel.add(txtName);
txtName.addActionListener(this);
addKeyListener(this);
txtName.addKeyListener(this);
}
set rowCount to 0 and add rows .this will remove existing rows and add new rows
tModel.setRowCount(0);
code
System.out.println("searching");
tModel.setRowCount(0);// *********************remove current rows to replace
tModel.setColumnIdentifiers(columnNames);
while(r.next()){
tModel.addRow(new Object[] {
r.getString("name")
});
}

Using a value to fire Jcombobox actionlistener instead of getselectedindex?

here is the Jcombobox it has two items name and id
public void ComboItem() {
chooser.removeAllItems();
chooser.addItem("Please Select...");
try {
String sql="select * from Patients_Details";
pst = conn.prepareStatement(sql);
rs=pst.executeQuery();
while (rs.next()) {
String id = rs.getString("Patient_ID"); // Get the Id
String name = rs.getString("Name"); // Get the Name
ComboItem comboItem = new ComboItem(id, name); // Create a new ComboItem
chooser.addItem(comboItem); // Put it into the ComboBox
String tmp=comboItem.getid();
}
} catch (SQLException sqle) {
System.out.println(sqle);
}
Jcombobox ActionListener code
private void chooserPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
Object selectedValue = chooser.getSelectedIndex();
try{
String sql="select * from Patients_Details where Patient_ID=? ";
pst=conn.prepareStatement(sql);
pst.setObject(1, selectedValue);
rs=pst.executeQuery();
if(rs.next()){
String add1=rs.getString("Patient_ID");
txtpatientid.setText(add1);
String add2=rs.getString("Name");
txtname.setText(add2);
String add3=rs.getString("Age");
txtage.setText(add3);
String add4=rs.getString("Gender");
txtgender.setText(add4);
String add7=rs.getString("Date");
txtdate.setText(add7);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,e );
}
}
My question is:
How can I use the id as a value to fire JCombobox listener instead of getSelectedindex Any help will be appreciated.
Use getSelectedItem() to obtain a reference to the currently selected ComboItem, and it's id; use getSelectedIndex() to obtain it's index.
Because setSelectedIndex() fires the combo's ActionListener, navigational controls such as ⊲Prev and Next⊳ buttons can delegate to the combo, as shown here:
Obtain the index from getSelectedIndex().
Increment or decrement the index.
Perform a range check on the index.
Delegate the selection to the combo via setSelectedIndex(index).
A particular implementation of ComboBoxModel, such as DefaultComboBoxModel, can be searched using iteration:
for (int i = 0; i < dcbm.getSize(); i++) {
ComboItem item = (ComboItem) dcbm.getElementAt(i);
// check item
}

Problems in removing records from database of jList

Hello I have the problem.. can anyone give me snippet? i have the table of MySql that display JList item so I can add the item easily but can't remove it from database? while pressing remove item?
I searched a lot no one has ever need of doing.. i wonder how its possible?
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","ubuntu123");
PreparedStatement stmt = null;
ResultSet rs = null;
String [] data;
data = new String[100];
int i=0;
DefaultListModel listmodel = (DefaultListModel) jList2.getModel();
int selectedIndex = jList2.getSelectedIndex();
if (selectedIndex != -1) {
listmodel.remove(selectedIndex);
String query = "delete from supplierinfo where companyname = ?";
stmt = (PreparedStatement) con.prepareStatement(query);
stmt.setInt(1, i);
stmt.execute();
con.close();
// i= i+1;
}
} catch(Exception e) {
System.out.println("3rd catch " +e);
}
}
You can save element in a variable when you remove it from ListModel.
After that you can get all important info about this item and use it in your query.
Use something like this:
YourObjectType obj = (YourObjectType) listmodel.remove(selectedIndex);
String query = "delete from supplierinfo where companyname = ?";
stmt = (PreparedStatement) con.prepareStatement(query);
stmt.setInt(1, obj.getCompanyName());
stmt.execute();
Use the ListModel#getElementAt(int) method with the currently selected index.
If you are certain your model only contains String instances, you can directly cast it to a String, then replace i with this string in stmt.setInt(1, i);

Categories

Resources