I am working on a project where I add the column names from mysql into jTable.
I want that when a name is added, the column should adjust its size according to the length of column name. I will make myself clearer, but first heres the existing code:
jTextArea1.setText(null);
tableModel.setColumnCount(0);
colwidth = 0;
try {
Class.forName("java.sql.DriverManager");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:" + GlobalParams.portvar + "/" + (String) jList1.getSelectedValue(), "" + GlobalParams.uservar, "" + GlobalParams.passvar);
Statement stmnt = (Statement) con.createStatement();
String query1 = "Use " + GlobalParams.dbvar;
stmnt.executeQuery(query1);
String query2 = "desc " + (String) jList2.getSelectedValue();
ResultSet rs = stmnt.executeQuery(query2);
while (rs.next()) {
fieldo = rs.getString("Field");
jTextArea1.append(fieldo + "\n");
}
Scanner scanner = new Scanner(jTextArea1.getText());
timeget();
jTextArea4.append(now + ": " + "/ Scanning Available feeds from table '" + (String) jList2.getSelectedValue() + "' / \n");
timeget();
jTextArea4.append(now + ": " + "/ Getting feeds from table '" + (String) jList2.getSelectedValue() + "' / \n \n");
if (scanner.hasNextLine()) {
scanner.nextLine();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
tableModel.addColumn(line);
jTable1.getColumnModel().getColumn(colwidth).setWidth(line.length());
colwidth++;
int end = jTextArea1.getLineEndOffset(0);
jTextArea1.replaceRange("", 0, end);
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
"colwidth" is a public static int and "fieldo" is a public static String.
What i want is, for ex.-> the string to be made into column is "asdadsasd123". I want that the column should adjust its width according to length of this string.
I have set the auto resize of table to off.
The table is enclosed in a scollpane. The layout of frame is Free Design.
I also did find the thread here-> Auto resizing the JTable column widths
but i cant seem to understand this code:
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width, width);
(Yeah, I aint very experienced with java).
And I also dont want to do anything with rows for now, just resize the columns.
Here is screenshot of Default->
Here is how I want it to be->
Please help,thanks.
You can use the Table Column Adjuster.
It will adjust the column width based on the size of the header the cell data or both.
Related
Here, resultSet.getInt() doesn't work, but I do not know what is wrong with my code.
I want to increment the value of the column (with the name as the variable 'attendance'). Using the SELECT statement I want to read the current value and by using UPDATE I want to increment the corresponding value by 1. But the problem is that int a = r.getInt("'" + attendance + "'"); doesn't work. It always returns the value 0 although the current value isn't 0 (e.g. 1). What is wrong with my code?
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:"+ x +".db");
s = c.createStatement();
r = s.executeQuery("SELECT '" + attendance + "' FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'");
while (r.next()){
int a = r.getInt("'" + attendance + "'");
int b = 1 + a;
String sql = "UPDATE viewer SET '" + attendance + "' = ? WHERE name = ? AND year = ? ";
p = c.prepareStatement(sql);
p.setInt (1,b);
p.setString (2,name);
p.setInt (3,year);
p.executeUpdate();
}
p.close();
c.close();
// r.getInt() value always 0
}
catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
Since you wrap the name of the column in single quotes, it is considered as the string literal 'attendance' and not the name of the column which is the value of the variable attendance.
Change to:
"SELECT " + attendance + " FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'"
(why do you concatenate the arguments name and year? Use placeholders ? just like the UPDATE statement)
and
"UPDATE viewer SET " + attendance + " = ? WHERE name = ? AND year = ? "
and
int a = r.getInt(attendance);
since you only have 1 column, you can use column index, instead of column names
int a = r.getInt(0);
So, I have something like this:
System.out.println("Enter owner's IC no. or plate no. : ");
String update = in.nextLine();
String sql = String.format("SELECT * FROM `vehicle` WHERE ic='%s' OR plate ='%s'",update,update);
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
System.out.println("IC and PLate No. not found....");}
while (rs.next()) {
regno = rs.getInt("regno");
name = rs.getString("name");
ic = rs.getString("ic");
plate = rs.getString("plate");
color = rs.getString("color");
year = rs.getInt("year");
make = rs.getString("make");
model = rs.getString("model");
capacity = rs.getDouble("capacity");
type = rs.getString("type");
maxload = rs.getDouble("maxload");
System.out.println(toString());
}
What I'm trying to do is, if data is found in the database, it will then print the following table for outputs that match.
Now, It is supposed to print out every output. But, it only prints out the first one.
I believe that the following code is the cause:
if(rs.next()) {
System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
System.out.println("IC and PLate No. not found....");}
I also faced the same problem, when used select query with Prepared statement.
For example-
String sqlquerySELECTAgentsWithParam = " select * from AGENTS WHERE AGENT_CODE = ( ? ) ";
it returned a single row, since I've used IF condition and then while(rs.next())
I couldn't print the single row, Hence, I've used do-while loop like below in order to print the first-row result. code snippet below- hope it will help !!
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(oracelDBUrl, oracleDBUser,oracleDBPwd );
if (conn != null) { System.out.println("Connected to the Oracle DB "); }
else { System.out.println("Failed to Connect to Oracle DB "); }
PreparedStatement pstmt = conn.prepareStatement(sqlquerySELECTAgentsWithParam);
pstmt.setString(1,"<agent_id>");
ResultSet rs = pstmt.executeQuery();
boolean returnResultrs = rs.next();
System.out.println("Fetched Result is = " +returnResultrs);
if(returnResultrs)
{
do {
System.out.println("Inside Do - While Loop");
System.out.println("AGENT_CODE = " + rs.getString(1)+ "has AGENT_NAME = " +rs.getString(2));
}
while(rs.next());
}
Use MessageFormat to format the output, and the counter to determine if empty result set, like so:
String strFormat = "RegNo. {0}\tName {1}\tIC {2}\tPlate No. {3}\tColor {4}\tYear {5}\tMake {6}\tModel {7}\tCapacity {8}\tType {9}\tMax Load {10}");
int counter = 0;
while (rs.next()) {
counter++;
regno = rs.getInt("regno");
name = rs.getString("name");
ic = rs.getString("ic");
plate = rs.getString("plate");
color = rs.getString("color");
year = rs.getInt("year");
make = rs.getString("make");
model = rs.getString("model");
capacity = rs.getDouble("capacity");
type = rs.getString("type");
maxload = rs.getDouble("maxload");
System.out.println(MessageFormat.format(strFormat, regno, name, ic, plate, color, year, make, model, capacity, type, maxload));
}
if (counter == 0) {
System.out.println("IC and PLate No. not found....");
}
So I see two issues here. The biggest one is this:
System.out.println(toString());
That calls the .toString() method on the current class, which will not output any of the data from your ResultSet. At least, not based on any of the code you've shown. You're storing all of the values coming back from the ResultSet in variables, but those variables don't appear to be getting used anywhere. You need to get those variables to your .println() somehow.
The second issue is that rs.next() moves the cursor forward one row. So when you do this:
if(rs.next()) {
That causes you to skip the first row. This is actually kind of tricky to fix, because there's no good way to tell whether or not a ResultSet is empty without calling .next(). The way I'd probably handle this is to pull all of the results into objects in a list, and then do all the printing based on the list, and not on the ResultSet itself.
I am trying to Create a table Model (i, y1, y2 .... yd) in Vertica using JAVA. Column i is integer and all others are REAL. I used the following code to create it. However it is showing syntax error at or near null. Does anybody know what that means? The connection works for the program.
public void createMODEL(int d)
{
int x;
try
{
Statement stmt = conn.createStatement();
String createquery = "CREATE TABLE MODEL ( "
+ "i integer primary key ";
for (x=1;x<=d;x++) createquery+= " , " + Y[x] + " REAL ";
createquery += ")";
stmt.executeUpdate(createquery);
}
catch (Exception e)
{
System.out.println("Error while executing create model query");
System.out.print(e);
System.exit(0);
}
}
Y is defined as follows -
String Y[]=new String[100];
I guess you should check if Y[x] is not null:
Statement stmt = conn.createStatement();
String createquery = "CREATE TABLE MODEL ( "
+ "i integer primary key ";
for (x=1;x<=d;x++) {
if (Y[x] != null) createquery+= " , " + Y[x] + " REAL ";
}
createquery += ")";
stmt.executeUpdate(createquery);
This works for me for MySQL. Try this.
String Y[] = new String[100];
Y[0] = "h";
Y[1] = "ha";
Y[2] = "hat";
Y[3] = "hati";
Y[4] = "hatim";
System.out.println("Your columns array : " + Arrays.deepToString(Y));
String createquery = "CREATE TABLE MODEL ( " + "i integer primary key ";
for (int i = 0; i < Y.length; i++) {
if (Y[i] != null)
createquery += " , " + Y[i] + " REAL ";
}
createquery += ");";
System.out.println("Your create query : " + createquery);
I am wondering how to read in a file and insert into a table in my data base. I written this:
String customerFile = "customer.txt";
Connection myConnect = ....
Statement mySt = myConnect.createStatement();
mySt.executeUpdate(..create customer table..);
int SSN;
String CNAME;
String GENDER;
int AGE;
String PROFESSION;
String line;
String[] tokens;
FileReader file1 = new FileReader(customerFile);
BufferedReader buffer1 = new BufferedReader(file1);
//throw away first line
line = buffer1.readLine();
//continue with rest of file
while((line = buffer1.readLine()) != null)
{
tokens = line.split(",");
SSN = Integer.parseInt(tokens[0]);
CNAME = tokens[1];
GENDER = tokens[2];
AGE = Integer.parseInt(tokens[3]);
PROFESSION = tokens[4];
String insertString = "insert into customer values ( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +")";
mySt.executeUpdate(insertString);
}
I thought this was the right way to insert into a table. However, the issue I am having with is that the variables aren't being read in the right way.
Example rows:
3648993,Emily,male,63,Consulting
5022334,Barbara,male,26,Finance
With the example above, I would want to have a table with 2 rows and 5 columns but the code I put on top gave me an error when it reaches the name. I am not sure where the issue is.
You should replace insertString with
myConnect = getConnection();
myConnect.setAutoCommit(false);
File file = new File(fileName);
fis = new FileInputStream(file);
pstmt = myConnect.prepareStatement("insert into customer( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +") values (?,?,?,?,?)");
pstmt.setString(1, SSN);
pstmt.setString(2, AGE);
....
pstmt.executeUpdate();
myConnect.commit();
Source : Insert text file into MySQL
Make sure you put quotes around string fields, so instead of:
String insertString = "insert into customer values ( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +")";
do:
String insertString = "insert into customer values ( " + SSN + ", '" + CNAME + "','" +
GENDER + "', " + AGE + ", '" + PROFESSION +"')";
Normally I do such things in two steps:
1) create a java class representing just one row of the textfile. This class is instantiated with a line from the txt-file and this single row is parsed and the fields are created, so I have for every single field a getter and a setter having the right fieldtype. within this class I'm able to perform tests and corrective actions if a field is wrong or even empty.
2) I create a Writer-class that reads the textfile line by line and writes every single line into the db, mostly starting with the second line, because the first line contains the header. I strictly use PreparedStatement and use batchwriting, at the end, when file looping is finished, write the batch to the DB with PreparedStatement.executeBatch() and then I close down all DB-objects.
I want to multiple price and quantity, so i can get the total, and put it in the table too. Can you help me? Because I already search other reference and add public Object getValueAt(int row, int column) {} but I got error so I delete it -_-
try {
String trans_id = txtNo.getText();
String menu_id = txtMID.getText();
String quantity = txtQuan.getText();
String menu_price = "";
Statement stmt;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM menu");
stmt.executeUpdate("insert into transaction (trans_id, menu_id, menu_price, quantity)"
+ "values ('" + trans_id + "','" + menu_id + "','" + menu_price + "','" + quantity + "')");
DefaultTableModel model = (DefaultTableModel) tblMenu.getModel();
if (rs.next()) {
txtNo.setText("" + rs.getString("trans_id"));
txtMID.setText("" + rs.getString("menu_id"));
menu_price = rs.getString("menu_price");
txtQuan.setText("" + rs.getString("quantity"));
model.addRow(new Object[]{trans_id, menu_id, menu_price, quantity});
}
} catch (Exception e) {
System.out.println("Failed" + e);
}
Really need your help.
You'll have to first convert price and quantity to numerical values, multiply them, and then convert the product back to a String. You can convert the text values of price and quantity using Integer.parseInt(String s). Or Double.parseDouble if your price is not an integer...you get the idea. Do that for both price string and quantity string. Then you can get the String value by String.valueOf(whatever your price * quantity value is), assuming you want to put that value into the table as a String.