i have a label and i want to upload with text from database, i wrote a method but its show just the first item from database, i want to see all item in column
try {
String sql="SELECT * FROM Arlista";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
while(rs.next()) {
arlab1.setText(rs.getString("nev"));
}
}catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
while(rs.next()) {
arlab1.setText(rs.getString("nev"));
}
...overwrites the content of arlab each iteration. What you probably want to do is some kind of append to the result for each row;
String result = "";
while(rs.next()) {
if(result.isEmpty()) result = rs.getString("nev");
else result = result + "/" + rs.getString("nev");
}
arlab1.setText(result);
Related
I have 3 jComboBox. The first one is for the Room Type. When I select Room Type on the first jComboBox it must show in the second jComboBox all the available room, but when I select one of the Room Type, an error pops u.p
Here is the code for actionperformed on the first jComboBox
first jComboBox actionperformed*
if(jComboBox13.getSelectedItem().toString().equals("SELECT")){
}else{
try{
String like = jComboBox13.getSelectedItem().toString();
String sql = "Select * From Room_Master\n" +
"inner join Room_Type on Room_Master.Room_Type_ID=Room_Type.Room_Type_ID\n" +
"where Room_Type = '"+like+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jComboBox14.removeAllItems();
jComboBox14.addItem("SELECT");
while(rs.next()){
String add1 = rs.getString("Room_No.");
jComboBox14.addItem(add1);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
second jComboBox actionperformed
if(jComboBox14.getSelectedItem().toString().equals("SELECT") | jComboBox14.getSelectedItem().toString().isEmpty()){
}else{
try{
String like = jComboBox14.getSelectedItem().toString();
String sql = "Select * from Bed_Master\n" +
"inner join Room_Master on Bed_Master.Room_ID=Room_Master.Room_ID\n" +
"where [Room_No.] = '"+like+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jComboBox15.removeAllItems();
jComboBox15.addItem("SELECT");
while(rs.next()){
String add1 = rs.getString("Bed_No.");
jComboBox15.addItem(add1);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
but after i select another Room type it will work
i tried to remove "combobox.removeAllItems();"
but it will keep addding all the items in the jCombobox
almost 1 week trying to figure it out can someone help please
When you call removeAllItems it fires the actionListener for jComoboBox14
and at this stage it will not have any Items so getSelected will return NULL
change your if to
if(jComboBox14.getItemCount() > 0 && (jComboBox14.getSelectedItem().toString().equals("SELECT") |
jComboBox14.getSelectedItem().toString().isEmpty())){
First of all. You should give your objects variables an useful name:
Ex: jComboBox13 --> JComboBox comboRoomsType = new JComboBox(); or whatever name you prefer.
Then, it would be nice to see all the code involved. I can't see where you initialize the ResultSet or PreparedStatement;
I GUESS the NullPointer comes from the select statement, when trying to retrieve the values.
if(jComboBox13.getSelectedItem().toString().equals("SELECT")){
}else{
try{
String like = jComboBox13.getSelectedItem().toString();
String sql = "Select * From Room_Master RM " +
"inner join Room_Type RT on RM.Room_Type_ID=RT.Room_Type_ID "
+"where Room_Type = '"+like+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jComboBox14.removeAllItems();
jComboBox14.addItem("SELECT");
//you can also check if there are values first.
while(rs.hasNext()){
rs.next();
String add1 = rs.getString("Room_No");
//You can also use
//String add1 = rs.getInt(number of column of <Room_No> );
jComboBox14.addItem(add1);
}
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
ta.setText is a TextArea where I want to show all my data from the database, after a button click. But with rs.get("name") I just output one value and it is always the last. How can I print out the whole table from the database, so all the information which are stored there?
try { String newquery = "SELECT * FROM kunden";
java.sql.PreparedStatement ps = con.prepareStatement(newquery);
rs = ps.executeQuery(newquery);
while (rs.next()){
ta.setText(rs.getString("name"));
ta.setText(rs.getString("nachname"));
}
}// try
catch(Exception e1) {
JOptionPane.showMessageDialog(null, "fail");
}
}//actionperformed
Either you build a string an then set that string using setText()
StringBuilder builder = new StringBuilder();
while (rs.next()) {
builder.append(rs.getString(“name”));
builder.append(“ “);
builder.append(rs.getString(“nachname”));
builder.append(“\n“);
}
ta.setText(builder.toString());
Or you use the append method that exists for TextArea
while (rs.next()) {
ta.append(rs.getString(“name”));
ta.append(“ “);
ta.append(rs.getString(“nachname”));
ta.append(“\n“);
}
I want to remove the data in database from jtable. I have 1 jTextField and 1 jButton. So when i click this selected row in table, the primary key wont set in my jTextField.
Is it possible to remove the data in database from jtable without jTextField and just a button?
Heres my code
try {
int row = table.getSelectedRow();
String id_ = (table.getModel().getValueAt(row, 1)).toString();
String sql ="SELECT id FROM 'mycredentials.sales' WHERE id= "+id_+"'";
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
PreparedStatement pst = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
jFrame_removeP.setText(rs.getString("id"));
}
} catch (SQLException e1) {
System.err.println(e1);
}
Random id number appears in my jTextField. And my table code is:
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String total = jFrame_total.getText().trim();
String st[] = {name, price, quantity, total};
model.addRow(st);
jFrame_gTotal.setText(Integer.toString(getSum()));
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement s = (Statement) connection.createStatement();
String sql = "INSERT INTO mycredentials.sales (name, price, quantity, total) VALUES ('"+jFrame_pName.getText()+"', '" + jFrame_pPrice.getText() + "','"+jFrame_quantity.getText()+"','"+jFrame_total.getText()+"')";
s.executeUpdate(sql);
} catch (SQLException e1) {
System.err.println(e1);
}
And my remove button is:
DefaultTableModel model1 = (DefaultTableModel) table_1.getModel();
int selectedRowIndex = table_1.getSelectedRow();
model1.removeRow(selectedRowIndex);
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement ps = (Statement) connection.createStatement();
String sql = "DELETE from mycredentials.sales where id ='" + jFrame_removeP.getText() + "'";
ps.executeUpdate(sql);
} catch (Exception ex) {
System.err.println(ex);
}
Do you mean like this? I didn't get exactly what you needed. Hope this helps.
private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {
String deleteQuery = "DELETE FROM SAMPLE WHERE USER_ID = ?";
try (Connection myCon = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = myCon.prepareStatement(deleteQuery);){
myPs.setInt(1,userID);
myPs.executeUpdate();
JOptionPane.showMessageDialog(null,"Records deleted");
}//end of try
catch (SQLException ex) {
DBUtilities.processException(ex);
}//end of catch
}
After search a record. You just click a record in the Jtable you want to delete. And just hit the Delete Button simple as that.
Just use a refresh method here if you want to remove the selected row. Fix your statement much better if you use Prepared Statement than Statements to avoid SQL injection.
I am having many rows in table and I ran the same query on my database which is MySql but java ResultSet is only giving the first row of the table. Here is my code.
public ArrayList<String> getAllAlbumsName(Integer uid) {
ArrayList<String>allAlbumsName = new ArrayList<String>();
try {
String qstring = "SELECT albumname FROM picvik_picture_album WHERE " +
"uid = '" + uid + "';";
System.out.println(qstring);
connection = com.picvik.util.MySqlConnection.getInstance().getConnection();
ptmt = connection.prepareStatement(qstring);
resultSet = ptmt.executeQuery();
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
resultSet.close();
ptmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return allAlbumsName;
}
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
If you would like to get all rows, it should be:
while(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
The while statement continually executes a block of statements while a particular condition is true
Note: As #BalusC commented, your code would introduce SQL Injection attack, it is better to use ptmt.set... Instead of constructing SQL String manually.
try while(resultSet.next()) {
instead of if (resultSet.next()) {
Change if (resultSet.next()) { to while (resultSet.next()) {
I want to get to the value I am finding using the COUNT command of SQL. Normally I enter the column name I want to access into the getInt() getString() method, what do I do in this case when there is no specific column name.
I have used 'AS' in the same manner as is used to alias a table, I am not sure if this is going to work, I would think not.
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count");
while(rs3.next()){
count = rs3.getInt("count");
}
Use aliases:
SELECT COUNT(*) AS total FROM ..
and then
rs3.getInt("total")
The answers provided by Bohzo and Brabster will obviously work, but you could also just use:
rs3.getInt(1);
to get the value in the first, and in your case, only column.
I would expect this query to work with your program:
"SELECT COUNT(*) AS count FROM "+lastTempTable+")"
(You need to alias the column, not the table)
I have done it this way (example):
String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"r#r.com"'";
int count=0;
try {
ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
while(rs.next())
count=rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//...
}
<%
try{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
if(con == null) System.out.print("not connected");
Statement st = con.createStatement();
String myStatement = "select count(*) as total from locations";
ResultSet rs = st.executeQuery(myStatement);
int num = 0;
while(rs.next()){
num = (rs.getInt(1));
}
}
catch(Exception e){
System.out.println(e);
}
%>
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
It's similar to above but you can try like
public Integer count(String tableName) throws CrateException {
String query = String.format("Select count(*) as size from %s", tableName);
try (Statement s = connection.createStatement()) {
try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
Preconditions.checkArgument(resultSet.next(), "Result set is empty");
return resultSet.getInt("size");
}
} catch (SQLException e) {
throw new CrateException(e);
}
}
}