I have made a jframe where i have to provide the medicine name and manufacturer name,,then click the search button..
and it will fetch the data from the mysql database and show in the jtable.
the jframe looks like this:
but when i am giving only medicine name and clicking search button.its not fetching the data ,its just fetching the column names from the database..:
and when i am giving both the values its giving :java.lang.illegalargumentexception:cannot set a null TableModel:
My srch_btnActionPerformed method is:
private void srch_btnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
/*if((jTextField1.getText())!=null || (jTextField2.getText())!=null)
{*/
String sql="select * from medicine where med_name=? or manufacturer_name=?";
try{
pst=conn.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
pst.setString(2,jTextField2.getText());
rs=pst.executeQuery();
if(rs.next()){
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
else
{
JOptionPane.showMessageDialog(null, "No entry with such names in DataBase!");
jTextField1.setText(null);
jTextField2.setText(null);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
/* */
}
Please help..
Try something like this:
//Global Declaration
private Vector<Vector<String>> data; //used for data from database
private Vector<String> header; //used to store data header
//Display only header on form load
//create header for the table
header = new Vector<String>();
header.add("Column1");
header.add("Column2");
...
model=new DefaultTableModel(data,header);
table = new JTable(model);
//in actionPerformed()
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==search){
data=get();
for(int i=0;i<count;i++){
Object[] d={data.get(i).get(0),data.get(i).get(1),data.get(i).get(2)};
model.addRow(d);
}
}
}
This will help you to get data from database
get(){
Vector<Vector<String>> doublevector = new Vector<Vector<String>>();
Connection conn = dbConnection();//Your Database connection code
PreparedStatement pre1 = conn.prepareStatement("select * from Table");
ResultSet rs1 = pre1.executeQuery();
while(rs1.next())
{
Vector<String> singlevector = new Vector<String>();
singlevector.add(rs1.getString(1));
singlevector.add(rs1.getString(2));
....
doublevector.add(singlevector);
}
return doublevector;
}
To pass null in your sql query,
You can replace
pst.setString(1, jTextField1.getText());
pst.setString(2,jTextField2.getText());
by following code:
if ( jTextField1.getText() == null)
pst.setNull(1, Types.VARCHAR);
else
pst.setString(1, jTextField1.getText());
if ( jTextField2.getText() == null)
pst.setNull(2, Types.VARCHAR);
else
pst.setString(2, jTextField2.getText());
Simply you can fix it.... in your database dont set null values for date add dates then this will be ok if there is any other that you didnt specifically mentioned length of the type those attributes also cannot be the null
Related
I have a problem with my data view, when showing my data from database to Jtable.
it showing like this,
The pesanan column is fully horizontal
what I want is the result showing like this So the pesanan column is show vertical with create new line using \n
this is my code to showing and get data to the table from phpmyadmin.
private void load_table() {
DefaultTableModel model = new DefaultTableModel();
model.addColumn("pembeli");
model.addColumn("pegawai");
model.addColumn("pesanan");
model.addColumn("harga");
model.addColumn("pembayaran");
model.addColumn("waktu");
//owing data from mysql to Jtable
try {
String sql = "select * from kopitable";
java.sql.Connection conn = (Connection) config.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while (res.next()) {
model.addRow(new Object[]{
res.getString(1), res.getString(2), res.getString(3), res.getInt(4), res.getString(5), res.getDate(6)
});
}
tabelnya.setModel(model);
} catch (Exception e) {
}
}
And this is my code when i insert data to phpmyadmin.
pesanandata.setText("\nAmericano : "+americano+"\nCapuccino : "+cappuccino+"\nmocha : "+mocha+"\nTopping : "+topping);
try{
String sql = " INSERT INTO kopitable VALUE ('"+namapembeli+"','"+pegawai+"','"+pesanandata.getText()+"','"+totalharga+"','"+pembayarannya.getText()+"','"+java.time.LocalDate.now()+"')";
java.sql.Connection conn=(Connection) config.configDB();
java.sql.PreparedStatement pst=conn.prepareStatement(sql);
pst.execute();
}catch (Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
i have some code that will save into two database but the other one can't saving into database. the one that can't to save is inserting multiple row data from jtable with 3 values but i have 5 columns in database because i need to fill it temporary with the other values are null. this is the code :
private void btnSimpanActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String sql="INSERT INTO pinjam VALUES('"+noPeminjaman.getText()+
"','"+noMember.getText()+"','"+tglPinjam.getText()+"',1)";
java.sql.Connection conn = (Connection)Config.configDB();
java.sql.PreparedStatement pst = conn.prepareStatement(sql);
pst.execute();
//Simpan ke pinjam_detil
int rows = tabelPinjam.getRowCount();
for(int row = 0; row<rows; row++){
String idBuku = (String)tabelPinjam.getValueAt(row, 0);
String tglTempo = (String)tabelPinjam.getValueAt(row, 2);
try{
String query = "INSERT INTO pinjam_detil (idpinjam,idbuku,tgl_tempo) "
+ "VALUES(?,?,?)";
java.sql.PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, noPeminjaman.getText());
stmt.setString(2, idBuku);
stmt.setString(3, tglTempo);
stmt.addBatch();
stmt.executeBatch();
}catch(Exception ex){}
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}catch(Exception e){}
resetForm();
}
Don't catch an exception and do nothing. Preferably, add a throws clause to the method, like so:
private void doThingie() throws SQLException {}
and if that's not an option, this should be in your catch block:
new RuntimeException(e);
because right now some error is happening and you can't tell because you're silently ignoring it.
Also, it's just stmt.execute();, not addBatch+executeBatch
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});
}
Can you populate more than one jTable with the same resultSet?
public void tableDisplay() {
String tableQuery = "SELECT foodQuantity,foodName FROM food ORDER BY RAND() LIMIT 3";
ResultSet rs;
PreparedStatement statement;
try {
statement = con.prepareStatement(tableQuery);
rs = statement.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
System.out.println(ex.toString());
}
}
The code compiles but the second table doesn't get any records from DB.
The point is that I need to select random items from mySql table and I want to display them in few jTables.
Without knowing too much about your code, I'd say that you need to call DbUtils.resultSetToTableModel(rs) once, and store the resulting table model in a local variable. Then, pass that local variable to the two setModel(...) methods
How I populate a JTable with resultSet
try{
playerTableModel = (DefaultTableModel)playerTable.getModel();
rs = controller.getPlayer();
while (playerTableModel.getRowCount() > 0);
int columns = playerTableModel.getColumnCount();
Object[] rows = new Object[columns];
while(rs.next()){
rows[0] = rs.getString(1);
rows[1] = rs.getString(2);
rows[2] = rs.getString(3);
rows[3] = rs.getString(4);
playerTableModel.addRow(rows);
}catch(Exception e){
e.printStackTrace();
}
Can't you just call same method for the second table too?
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);