Formatting in a textArea append. Java - java

how do you format text in a textArea when appending it?
try{
//establish connection to database
connection= DriverManager.getConnection(DATABASE_URL, "Hotel", "1234");
//create statement for querying database
statement = connection.createStatement();
// statement.executeUpdate("INSERT INTO TBLSTUDENT VALUES("+id+",'"+name+"','"+course+"',"+age+")");
//query database
resultSet = statement.executeQuery("SELECT * FROM Customer");
//process query results
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
textArea.append("Hotel Database: \n");
for(int i=1; i<=numberOfColumns; i++){
textArea.append(metaData.getColumnName(i));//"%-8s\t",
}
System.out.println();
while(resultSet.next()){
for(int i=1; i<=numberOfColumns;i++){
textArea.append(resultSet.getObject(i).toString());
}
System.out.println();
}
}catch(SQLException sqlException){
sqlException.printStackTrace();
}
Right now the output is that it only appends into one line.
And it should be
Column 1-Column 2-Column 3
data1-data 2-data 3
I tried using the formatting %-8s\t but it doesn't work on .append()

Generally speaking, JTextArea's not the best choice, you should be using a JTable
See How to Use Tables for more details
However, try using something more like textArea.append(String.format("%-8s\t", metaData.getColumnName(i))); instead
You will also need to append a new line character (\n) between the lines

Related

Problem with diacritic, getting data from database java

I have MySQL database, where I have saved data and some words have diacritics.
This is my function how to get data from database.
public List<RowType> getData(String query){
List<RowType> list = new ArrayList<>();
try{
connect();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()){
StringBuilder str = new StringBuilder();
for(int i = 1; i <= getCountColumns(resultSet); i++){
if(i==1) str.append(resultSet.getString(i));
else str.append("," + resultSet.getString(i));
}
list.add(new RowType(str.toString()));
}
}
catch(Exception e){
System.out.println("Chyba při získavání údajů z databáze.");
System.out.println(e);
Console.print("Chyba při získavání údajů z databáze.");
Console.print(e.toString());
}
finally{
disconnect();
}
return list;
}
As parameter i send this query.
List<RowType> list = connection.getData("Select id from countries where name = 'Česko'");
But it doesn´t find anything, because i have diacritic in the query ("Česko"). I try it without diacritic and it works. So don´t you know how to fix it to work with accents too?
Can you try to add a few more queries before executing your main query?
so it will look something like:
connect();
Statement statement = connection.createStatement();
String query2 = "SET NAMES 'utf8'";
statement.execute(query2);
query2 = "SET CHARACTER SET 'utf8'";
statement.execute(query2);
ResultSet resultSet = statement.executeQuery(query);
if the above does not work for you, then maybe there is an issue with your database settings; if that's the case, you can refer to the answer here

Update one column from table and insert new rows. sqlite, java

I have some problems to modify data from a table.
I need to update an entire column from a specific table and if there's no sufficient rows I need to insert more.
More exactly, the user will be able to modify data from interface, in a text area that contains current data from db.
I put all the text in a list, each line representing an element of the list.
In a certain column, I must go through each row and modify it with a list item. If there are more lines in the text area than number of rows in that table, I need to insert new ones, which will contain the remaining items from the list.
I would be grateful if someone could give me some help.
Thanks!
#FXML
public void modify() throws SQLException {
String col= selectNorme.getValue().toString();
String text=texta.getText();
List<String> l1notes= new ArrayList<>( Arrays.asList( text.split("\r\n|\r|\n") ));
Statement stmt=null;
String client = this.clientCombobox.getValue().toString();
String tab1Client= client+ "_" +this.selectLang1.getValue().toString();
String query="SELECT * FROM "+tab1Client+" WHERE ["+ selectNorme.getValue().toString()+ "]= "+col+"";
String sqlUpdate1= "UPDATE ["+tab1Client+"] SET ["+ this.selectNorme.getValue().toString() +"] = ?";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement modif=conn.prepareStatement(sqlUpdate1);
int i=0;
if (rss.next()) {
stmt = conn.createStatement();
rss = stmt.executeQuery(query);
stmt.executeUpdate(sqlUpdate1);
modif.setString(1, l1notes.get(i));
i++;
modif.execute();
}
else {
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO ["+this.clientCombobox.getValue().toString()+"_"+this.selectLang1.getValue().toString()+"] (["+ this.selectNorme.getValue().toString() +"]) values (?)" );
for (int row=i; row< l1notes.size(); row++)
{
pstmt.setString(1, l1notes.get(row));
pstmt.executeUpdate();
}
}
}
finally {
try {
if (conn !=null)
conn.close();
}
catch (SQLException se){
se.printStackTrace();
}
}
}

Retrieve & Display different rows of a Mysql table to a GUI form in java

I want to retrieve rows from my database one by one and view it in jtextfields present in a GUI form which I made. I am able to retrieve the first row, but never the second or third or fourth,etc.
Please help. If you need more information please ask
String SQL = "select CATEGORY,ITEM,QTY,Avg_Price from (select CATEGORY,ITEM,QTY,AVG_PRICE, rownum rw from final_inv) where rw ="+i+"";
rs = stmt.executeQuery(SQL);
if(rs.next()){
jTextField1.setText(rs.getString(1));
jTextField2.setText(rs.getString(2));
jTextField3.setText(rs.getString(3));
jTextField4.setText(rs.getString(4));
}
i++;
rs=stmt.executeQuery(SQL);
if(rs.next()){
jTextField5.setText(rs.getString(1));
jTextField6.setText(rs.getString(2));
jTextField7.setText(rs.getString(3));
jTextField8.setText(rs.getString(4));
}
I am new to java so pelase excuse my newbie mistakes
Don't directly set text to your jTextField intance inside your loop otherwise your jTextField won't get updated. But temp those text in variable, then set it to jTextField after your loop ends. And don't use 'if' rather 'while' , because you want to iterate each row in database
String SQL = "select CATEGORY,ITEM,QTY,Avg_Price from (select CATEGORY,ITEM,QTY,AVG_PRICE, rownum rw from final_inv) where rw ="+i+"";
String text [] = new String [10]; // just for temp the strings
rs = stmt.executeQuery(SQL);
while(rs.next()){
text[1] +=rs.getString(1);
text[2] +=rs.getString(2);
text[3] +=rs.getString(3);
text[4] +=rs.getString(4);
}
jTextField1.setText(rs.getString(text[1] ));
jTextField2.setText(rs.getString(text[2] ));
jTextField3.setText(rs.getString(text[3] ));
jTextField4.setText(rs.getString(text[4] ));
i++;
rs=stmt.executeQuery(SQL);
while (rs.next()){
text[1] +=rs.getString(1);
text[2] +=rs.getString(2);
text[3] +=rs.getString(3);
text[4] +=rs.getString(4);
}
jTextField5.setText(rs.getString(text[1]));
jTextField6.setText(rs.getString(text[2]));
jTextField7.setText(rs.getString(text[3]));
jTextField8.setText(rs.getString(text[4]));

JTable Repeat Result

My problem is that I have a JTable that always prints the first line repeatedly, and ignores the following data. I think that is the problem code.
I do a query and converts it to a list to populate my JTable. I ask you to analyze my code to see if it is right.
try{
EntityManager em = EntityManagerUtil.getEntityManager();
em.getTransaction().begin();
Query query_resultados = em.createQuery("FROM "
+ "Resultados WHERE res_codigo LIKE "+aux);
List<Resultados> lista_resultados =
(List<Resultados>) query_resultados.getResultList();
for(int i=0; i<lista_resultados.size(); i++){
Resultados resultado = lista_resultados.get(i);
System.out.println("Teste: "+lista_resultados.get(i).getRes_anti_hbc_hbs());
System.out.println("i= "+i);
model.addRow(new Object[] {resultado.getRes_anti_hbc_hbs(),
resultado.getRes_anticorpos_irregulares(),
resultado.getRes_chagas(), resultado.getRes_codigo(),
resultado.getRes_data(), resultado.getRes_ggpd(),
resultado.getRes_hbs_aq(), resultado.getRes_hcv(),
resultado.getRes_hiv(), resultado.getRes_htlv_i_ii(),
resultado.getRes_malaria(), resultado.getRes_responsavel(),
resultado.getRes_sifilis(), resultado.getRes_t_mancha(),
resultado.getRes_tpg()});
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro: "+e);
}
In Java it is common to iterate over a Java ResultSet by using something like this:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String firstColVal = rs.getString(1);
}
rs.next() ensures in this context that the next lines is fetched until all lines are done.

Java ResultSet Missing Final Record if Where Clause included in SQL command

I have a very simple java application intended to reach into a db and pull out a resultset based on an input on a java form. However, any parameters added to the SQL Statement end with a loss of the final record in the recordset (though it does seem to pull the proper result.)
The below code results in my entire dataset, with example at the top (as expected.)
Name|Location|Details
A|Here|7854
A|There|7854
B|Here|8761
C|Gone|5312
public void actionPerformed(ActionEvent e) {
try {
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=$DBname;user=$user;password=$password";
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(driver).newInstance();
Connection dbconn = DriverManager.getConnection(url);
Statement stmt = dbconn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT * from schema.table");
tblServers.setModel(buildTableModel(rs));
dbconn.close();
} catch (Exception f) {
System.err.println("Downloading Servers from the Database Failed! ");
System.err.println(f.getMessage());
}
}
private DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData rsmetaData = rs.getMetaData();
//Get Column Names
int numCols = rsmetaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
for (int column = 1; column <= numCols; column++) {
columnNames.add(rsmetaData.getColumnName(column));
}
//Iterate through rows
Vector<Object> data = new Vector<Object>();
while (rs.next()) {
Vector<Object> rows = new Vector<Object>();
for (int colIndex = 1; colIndex <= numCols ; colIndex++) {
rows.add(rs.getObject(colIndex));
}
data.add(rows);
}
return new DefaultTableModel(data, columnNames);
}
}
);
Now if I change nothing but the SQL line to any variant with a "where" clause, like:
rs = stmt.executeQuery("SELECT * from schema.table where name = 'A'");
I get:
Name|Location|Details
A|Here|7854
Or if searched for B, I get no results:
Name|Location|Details
|||
Any ideas are appreciated; I'm sure this is something extremely simple.
#Sasha: Yes, I am sure I am getting 1 result. I have tried with many permutations and it always results in either a blank resultset (but with accurate headers) or headers, and resultset, minus the final row.
#PM77-1: As soon as the code spits back the return (data, ColumnNames) my JTable has the resultset visible to the user.
#Glenn: On your suggestion, I added System.out.println(data) and 'System.out.println(rs)' to just before the 'return new DefaultTableModel'. The output is [] and SQLServerResultSet:1, respectively
#JohnnyAW The results for that with a where clause are the same as my comment above - no "tests" appear in the syslog. When I remove the where clause, I get a bunch of syslog entries with "test" prefacing my records.
Correction: I get "testtesttest" to the sum of 8 tests, my entire testing recordset. One test gets missed when I have a Where clause.

Categories