How to escape \n on Jtable - java

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());
}

Related

java - cant insert multiple data to database

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

Parameter index out of range when filtering mysql data to show in a JTable

Good Day
I am trying to retrieve data from a database into jTable. When the user writes in the textfield the required data it displays it in the table.
What I get is
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
Here is my codes
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
String Sql="Select recName,phoneNo,quali,major,Uni,status,IntDate,interviewer from rect ";
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setRowCount(0);
while(rs.next()){
Object obj [] = {
rs.getString("recName"),
rs.getString("phoneNo"),
rs.getString("quali"),
rs.getString("major"),
rs.getString("Uni"),
rs.getString("status"),
rs.getDate("IntDate"),
rs.getString("interviewer")
};
model.addRow(obj);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Any Ideas?
You have missed some parameter in the where clause:
Query: Select
recName,phoneNo,quali,major,Uni,status,IntDate,interviewer from rect
where something = ?
String Sql="Select recName,phoneNo,quali,major,Uni,status,IntDate,interviewer from rect where something = ?";
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();

Can't populate jtable with mysql "like" statement

I am building an application in which you can save deals to database. I'd like to search deals in my database and populate my jtable with relevant results. I want to query my database on keyrelease event. I know it is not an efficient method but I am curious why I can't get it to work.
Below is a sample code that tries to query a database table with ID and country names. There are only 3 country names that start with "D". Somehow I can get country names printed out but can't get them to populate jtable.
The error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" I can't get ResultSet rs1 into a Object[][] . It works fine if I do System.out.println(rs1.getString("Name")
Below is the code -
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String columnName[] = new String[] { "Name" };
Object oss[][] = new Object[3][];
ResultSet rs1 = null;
int li = 0;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection con = DriverManager.getConnection(Url, User, Password);
Statement st = con.createStatement();
String query = "SELECT * from unit.cntry WHERE Name LIKE '" + abc.getText() + "%';";
rs1 = st.executeQuery(query);
} catch (Exception e) {}
try {
while (rs1.next()) {
oss[li][0] = rs1.getString("Name");
li++;
}
myTable.setModel(new DefaultTableModel(oss, columnName));
} catch (SQLException ex) {
System.out.println(ex.toString());
} finally {
try {
if (rs1 != null) rs1.close();
} catch (SQLException e) {}
}
}
oss[li] = new Object[1];
oss[li][0] = rs1.getString("Name");
Other data structures might be more appealing.

java.lang.illegalargumentexception:cannot set a null TableModel

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

How to delete a record (string) JAVA and MYSQL

I successfully can delete an integer but when I tried to make it a STRING it says
"unknown column itemtodelete in where clause but my ITEMTODELETE is a STRING declared in the database not an integer how much It doesn't delete a STRING?
below is my code:
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
int del = (prompt):
if (del == JOptionPane.YES_OPTION){
DelCurRec();
}
}
public void DelCurRec() {
String id = field.getText();
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
try {
Class.forName(connectio);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);
}
Statement stmt = null;
Connection con = null;
//Creates connection to database
try {
con = DriverManager.getConnection("Connection");
stmt = con.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);
}
//Execute the SQL statment for deleting records
try {
stmt.executeUpdate(SQL);
//This closes the connection to the database
con.close();
//This closes the dialog
JOptionPane.showMessageDialog(null,"Deleted Succesfully","Delete Successful",JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);
}
}
Do NOT use a Statement use a PreparedStatement instead, otherwise your application will be vulnerable to SQL injections. E.g. someone enters a string like: "'; drop table inventory; --"
The corresponding prepared statment would look something like:
String SQL = "DELETE FROM inventory WHERE ItemCode = ? ";
PreparedStatement pstmt = null;
// get a connection and then in your try catch for executing your delete...
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeUpdate();
try changing the line:
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
to
String SQL = "DELETE FROM inventory WHERE ItemCode = '"+id+"' ";
I think you need to pass Integer.parseInt(id) and not id...assuming your id is int
This worked for me:
Statement stmt=con.createStatement();
stmt.executeUpdate("DELETE FROM student WHERE reg_number='R18854';");

Categories

Resources