I fixed the problem I had with my rs, and now here's my code:
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
String resultado = "";
resultado = rs.getString(i);
columnValue += resultado;
}
columnValue += "), (";
}
String sub = columnValue.substring(0, columnValue.length() - 3);
jTextPane2.setText(jTextPane2.getText() + sub);
sub = "";
columnValue = "";
jTextField1.setText("");
and the Result I get is this:
(id_tlf, cod_area)
(1+58), (2+104), (3+100)
How should I edit my code so that it looks like this:
(id_tlf, cod_area)
(1, +58), (2, +104), (3, +100)
If you see, I want to add a comma after the first rs and not on the 2nd one
Related
is it possible to update multiple rows in jtable using batch.. if yes then how? if not is there any other solution? i mean update statement here not insert!
thanx in advance
try {
int rows = jTable1.getRowCount();
cc.c.setAutoCommit(false);
String sql = "Insert into employyes(idemployyes,employyesName,employyesAge,employyesAddress) values (?,?,?,?)";
cc.pst = cc.c.prepareStatement(sql);
for (int row = 0; row < rows; row++) {
String idemployyes = (String) jTable1.getValueAt(row, 0);
String employyesName = (String) jTable1.getValueAt(row, 1);
String employyesAge = (String) jTable1.getValueAt(row, 2);
String employyesAddress = (String) jTable1.getValueAt(row, 3);
cc.pst.setString(1, idemployyes);
cc.pst.setString(2, employyesName);
cc.pst.setString(3, employyesAge);
cc.pst.setString(4, employyesAddress);
cc.pst.addBatch();
cc.pst.executeBatch();
cc.c.commit();
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
here is the answer:
try {
int rows = jTable1.getRowCount();
cc.c.setAutoCommit(false);
String sqlquery = "UPDATE employyes\n"
+ "SET employyesName = ?,employyesAge = ?, employyesAddress = ?\n"
+ "WHERE idemployyes = ?;";
cc.pst = cc.c.prepareStatement(sqlquery);
for (int row = 0; row < rows; row++) {
String idemployyes = (String) jTable1.getValueAt(row, 0);
String employyesName = (String) jTable1.getValueAt(row, 1);
String employyesAge = (String) jTable1.getValueAt(row, 2);
String employyesAddress = (String) jTable1.getValueAt(row, 3);
cc.pst.setString(1, employyesName);
System.out.println(employyesName);
cc.pst.setString(2, employyesAge);
System.out.println(employyesAge);
cc.pst.setString(3, employyesAddress);
System.out.println(employyesAddress);
cc.pst.setString(4, idemployyes);
System.out.println(idemployyes);
cc.pst.addBatch();
cc.pst.executeBatch();
cc.c.commit();
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
Right now my output of count is 0 for every element in combobox i.e it is like B10,B20,B30(B is the default value,next term is the value from database, and 0 is showing the count in this concatenated string)...my count is not increasing
What should I do so that my count increase when I select a value from Jcombobox
and press the button i.e.I get B10,B11,B12,B20,B21,B22,B30,B31,B32
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if (str.equals("GENERATE PART NO. :")) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
st = con.createStatement();
String s = "select value from user1 where Userdata='" + jc.getSelectedItem() + "'";
rs = st.executeQuery(s);
t1.getText();
if (rs.next()) {
int j = 0;
String add1 = rs.getString("value");
t1.setEditable(false);
String str9 = new String();
str9 = "B" + add1; //B is the default value, add1 is the value from database
String str10 = new String();
str10 = str9 + j;
String query = "select MC from final";
ResultSet rs1 = st.executeQuery(query);
while (rs1.next()) {
if (str10.equals(rs1)) {
j = j + 1;
j=new Integer(j+1);
t1.setText(str10);
} else {
t1.setText(str10);
}
}
}
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
String s1 = ("insert into final(MC)values(?)");
PreparedStatement pstm = con.prepareStatement(s1);
pstm.setString(1, t1.getText());
int rowi = pstm.executeUpdate();
if (rowi > 0) {
JOptionPane.showMessageDialog(null, "DATA INSERTED");
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
The answer is quite simple:
Move str10 = str9 + j; into while body.
Your (fragment of the) code should look like:
/* if */while(rs.next()) {
int j = 0;
String add1 = rs.getString("value");
t1.setEditable(false);
// String str9; //= new String(); redundant
String str9 = "B" + add1; //B is the default value add1 is the value from database
String str10 = str9;
String query = "select MC from final";
ResultSet rs1 = st.executeQuery(query);
while (rs1.next()) {
if (str10.equals(rs1.getString("MC")) {
j++; //j = j + 1;
// j=new Integer(j+1); you simply increment j twice
str10 = str9 + j;// EDITED LINE!
}
t1.setText(str10);
}
}
How do I to write an entire table to a flat file (text file) using jdbc? So far I've attempted the following:
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM tablename");
BufferedInputStream buffer;
FileOutputStream out = new FileOutputStream("flatfile.txt");
while(result.next() )
{
buffer = new BufferedInputStream(result.getBinaryStream("????") );
byte[] buf = new byte[4 * 1024]; //4K buffer
int len;
while( (len = buffer.read(buf, 0, buf.length) ) != -1 )
{
out.write(buf, 0, len );
}
}
out.close();
"????" is just my placeholder. I am stuck on what to pass in as an argument.
You can get all the column names and the entire data from your table using the code below.
writeToFile method will contain the logic to writing to file (if that was not obvious enough :) )
ResultSetMetaData metadata = rs.getMetaData();
int columnCount = metadata.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
writeToFile(metadata.getColumnName(i) + ", ");
}
System.out.println();
while (rs.next()) {
String row = "";
for (int i = 1; i <= columnCount; i++) {
row += rs.getString(i) + ", ";
}
System.out.println();
writeToFile(row);
}
Here's how I dump a table from a JDBC connection, very useful for debugging if you want to see all rows that are in an in memory (ex: HSQL) DB for instance:
public static void spitOutAllTableRows(String tableName, Connection conn) {
try {
System.out.println("current " + tableName + " is:");
try (PreparedStatement selectStmt = conn.prepareStatement(
"SELECT * from " + tableName, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = selectStmt.executeQuery()) {
if (!rs.isBeforeFirst()) {
System.out.println("no rows found");
}
else {
System.out.println("types:");
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
System.out.print(rs.getMetaData().getColumnName(i + 1) + ":" + rs.getMetaData().getColumnTypeName(i + 1) + " ");
}
System.out.println();
while (rs.next()) {
for (int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++) {
System.out.print(" " + rs.getMetaData().getColumnName(i) + "=" + rs.getObject(i));
}
System.out.println("");
}
}
}
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
output is like
current <yourtablename> is:
types:ID:INT YOURCOLUMN1:VARCHAR YOURCOLUMN2:VARCHAR
ID=1 YOURCOLUMN1=abc YOURCOLUMN2=null
ID=2 YOURCOLUMN1=def YOURCOLUMN2=ghi
...
result.getBinaryStream("????") will only return for the value for that column as you put as placeholder.
If you want to get all the column, you need to use ResultSetMetaData from ResultSet
ResultSetMetaData metadata = resultSet.getMetaData();
int columnCount = metadata.getColumnCount();
for (int i=1; i<=columnCount; i++)
{
String columnName = metadata.getColumnName(i);
System.out.println(columnName);
}
Hi I have an arraylist of strings, I want to show the content of the arraylist on JLabel separated by a space or comma. But it shows me only one String, the last one.
public void ShowMovie(int idMovie) throws SQLException, IOException {
int ID = idMovie;
String IDMOVIE = Integer.toString(ID);
IDMovieLabel.setText(IDMOVIE);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Cover.class.getName()).log(Level.SEVERE, null, ex);
}
con = DriverManager.getConnection("jdbc:mysql://localhost/whichmovie", "Asis", "dekrayat24");
String sql = "SELECT Title,Year,Country,recomendacion,Cover,Rating,NameDirec,Name FROM movie "
+ "Inner join direction on (movie.idMovie=direction.idMovie5)"
+ "Inner join director on (direction.idDirector=director.idDirector)"
+ "Inner join cast on (movie.idMovie=cast.idMovie4)"
+ "Inner join actor on (cast.idActor=actor.idActor)"
+ "where idMovie= '" + ID + "'";
st = con.prepareStatement(sql);
rs = st.executeQuery(sql);
while (rs.next()) {
String titulo = rs.getString(1);
int añoInt = rs.getInt(2);
String año = Integer.toString(añoInt);
byte[] imagedataCover = rs.getBytes("Country");
byte[] imagedataCover1 = rs.getBytes("Cover");
format = new ImageIcon(imagedataCover);
format2 = new ImageIcon(imagedataCover1);
TituloLabel.setText(titulo);
AñoLabel.setText(año);
CountryLabel.setIcon(format);
DirectorLabel.setText(rs.getString(7));
int Recomend = rs.getInt(4);
String Recom = Integer.toString(Recomend);
RecommendLabel.setText(Recom);
int Rating = rs.getInt(6);
String Rat = Integer.toString(Rating);
RatingLabel.setText(Rat);
starRater1.setSelection(Rating);
starRater1.setEnabled(false);
Image imgEscalada = format2.getImage().getScaledInstance(CoverLabel.getWidth(),
CoverLabel.getHeight(), Image.SCALE_SMOOTH);
Icon iconoEscalado = new ImageIcon(imgEscalada);
CoverLabel.setIcon(iconoEscalado);
ArrayList<String> actors = new ArrayList<>();
actors.add(rs.getString(8));
System.out.println(actors);// Here i can see i get 9 actors.
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : actors) {
if (!first) {
sb.append(' ');
}
sb.append(s);
first = false;
}
CastLabel1.setText(sb.toString());
}
rs.close();
st.close();
con.close();
}
Any help ?
Edit:unfortunately no solution has helped me, maybe I'm doing something wrong in the method, I post the full method.
String text = "";
for(int i = 0; i < actors.size(); i++){
text = text + actors.get(i);
if(i < actors.size() - 2){
text = text + ", ";
}
}
CastLabel1.setText(text);
The problem is you are resetting the label for each step in the for loop, and not creating a cumulative result. See below:
StringBuilder buf = new StringBuilder();
for(int i = 0; i < actors.size(); i++){
buf.append(actors.get(i));
if(i < actors.size() -1){
buf.append(" ");
}
}
CastLabel1.setText(buf.toString())
You should build the string you want to show first then set it to the text of the label:
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : actors) {
if (!first)
sb.append(' ');
sb.append(s);
first = false;
}
CastLabel1.setText(sb.toString());
What you're currently doing is changing the entire label text during each iteration, so the final text is that of the last element in the list.
Here is a method that I am writing for a class. It is supposed to refresh a table with data obtained from quering a database. I get an error when trying to scan through the line newResult.next().
I tried debugging, but that doesn't show me anything. the code prints out the line "In while loop", so I know that the problem is the in the line right after it. I constantly get the error, "After start of result set". I tried looking at my code, but it doesn't look like I am calling that method anywhere else either. thanks.
public void refresh()
{
try
{
Statement statement = gtPort.getConnection().createStatement();
//this query is also not working, not really sure how it works.
String query = "SELECT CRN, Title, Instructor, Time, Day, Location, Letter"
+ "FROM Section S WHERE CRN NOT IN "
+ "(SELECT CRN FROM Registers R WHERE Username = \""
+ gtPort.userName + "\")";
System.out.println(query);
statement.executeQuery(query);
System.out.println("Statemetne execute ");
// String[] columns = {"Select", "CRN", "Title", "Instructor", "Time",
// "Days", "location", "Course Code*", "Section"*,"Mode of Grading*"};
ResultSet result = statement.getResultSet();
System.out.println("created result");
data = new Object[10][10];
System.out.println("created data");
Object[] values = new Object[10];
System.out.println("created values");
// values[0] = null;
if (result == null)
{
System.out.println("result is null");
}
String[] titles = new String[100];
//for (int i = 1; i< table.getColumnCount(); i++)
//model.removeRow(i);
//table.removeAll();
//table.repaint()
model.setRowCount(0);
table = new JTable(model);
model.setRowCount(35);
for (int i = 1; result.next(); i++)
{
values[1] = Boolean.FALSE;
for (int j = 2; j< 8; j++)
values[j] = result.getString(j);
titles[i] = result.getString(2);
model.insertRow(i, values);
}
String[] codes = new String[table.getColumnCount()];
System.out.println("count: " + titles.length);
for (int i = 1; I < titles.length; i++)
{
query = new String("SELECT C.Code FROM Code C WHERE C.Title = \""
+ titles[i] + "\"");
//this is a different query to check for titles.
statement.executeQuery(query);
System.out.println(query);
ResultSet newResult = statement.getResultSet();
// codes[i] = newResult.getString(1);
if (newResult == null)
{
System.out.println("it is null");
break;
}
//this is the loop where it breaks.
while(newResult.next());
{
System.out.println("in while loop");
//this line prints, so the next line must be the problem.
model.setValueAt(newResult.getString(1), i, 8);
}
System.out.println("nr: \t" +newResult.getString(1));
}
System.out.println("before table");
table = new JTable(model);
System.out.println("created table");
}
catch (Exception exe)
{
System.out.println("errored in course selection");
System.out.println(exe);
}
}
Write ResultSet rs = statement.executeQuery(query); instead. getResultSet() is called when you have got more then one result sets from executed statement.
Don't use constructor new String() for creating String. Simply write:
String new = "content";
You cannot predict how much your first query will return so don't create arrays with stated size but use better ArrayList:
Code:
//creation
List<Object> values = new ArrayList<Object>();
List<String> titles = new ArrayList<String>();
//usage - adding
values.add(someObject);
//usage - getting
for (String title : titles)
//or
titles.get(byIndex);