Creating string by combining value from combobox and serial count - java

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

Related

all listview data insert only one row

I have a ListView with multiple rows. When I insert the entries in the ListView into an sql database, all the entries get inserted into a single row.
I get all the entries from the view with a String builder.
How can I solve this problem?
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
StringBuilder sb3 = new StringBuilder();
//get data form text view
for(int i=0; i<simpleAdapter.getCount(); i++) {
String a = ((TextView) findViewById(R.id.al)).getText().toString();
String b = ((TextView) findViewById(R.id.sh)).getText().toString();
String c = ((TextView) findViewById(R.id.acc)).getText().toString();
simpleAdapter.getItem(i).toString();
sb.append(a);
sb.append("\n");
sb2.append(b);
sb2.append("\n");
sb3.append(c);
sb3.append("\n");
}
String text = sb.toString();
String text2 = sb2.toString();
String text3 = sb3.toString();
//my sql connection insert query
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "Error in connection with SQL server", Toast.LENGTH_LONG).show();
} else {
String query = "INSERT INTO suigen.TransAlmiraShelf (Almira, Shelf, AccessionNo) VALUES('" + String.valueOf(text) + "','" + String.valueOf(text2) + "','" + String.valueOf(text3) + "')";
Statement stmt = con.createStatement();
stmt.execute(query);
Toast.makeText(Main13Activity.this, "Your Data Successfully Saved", Toast.LENGTH_LONG).show();
}
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Exceptions", Toast.LENGTH_LONG).show();
}
Get the list of Values form the table usng JDBC
Connection connection = DriverManager.getConnection("URL", "USERNAME",
"PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from
table");
ResultSet resultSet = statement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
int type = resultSetMetaData.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
System.out.println(resultSet.getString(i));
} else {
System.out.println(resultSet.getLong(i));
}
}
System.out.println("-----------");
}
}
The problem is that you are adding all the information into the string builders before you insert into the sql database.
You can fix this by getting the information and immediately insert it into the database:
ListView listView = ((ListView) findViewById(R.id.listView));
try {
Connection con = connectionClass.CONN();//first you do the connection
if (con == null) {
Toast.makeText(getApplicationContext(), "Error in connection with SQL server", Toast.LENGTH_LONG).show();
} else {
for(int i=0; i<simpleAdapter.getCount(); i++) {//then create the information you're going
View row = simpleAdapter.getView(i, null, listView);
String a = ((TextView) row.findViewById(R.id.al)).getText().toString();
String b = ((TextView) row.findViewById(R.id.sh)).getText().toString();
String c = ((TextView) row.findViewById(R.id.acc)).getText().toString();
sb.append(a);
sb.append("\n");
sb2.append(b);
sb2.append("\n");
sb3.append(c);
sb3.append("\n");
String text = sb.toString();
String text2 = sb2.toString();
String text3 = sb3.toString();
String query = "INSERT INTO suigen.TransAlmiraShelf (Almira, Shelf, AccessionNo) VALUES('" + String.valueOf(text) + "','" + String.valueOf(text2) + "','" + String.valueOf(text3) + "')";
Statement stmt = con.createStatement();
stmt.execute(query);
Toast.makeText(Main13Activity.this, "Your Data Successfully Saved", Toast.LENGTH_LONG).show();
}
}
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Exceptions", Toast.LENGTH_LONG).show();
}
The reason you got all the data in one row is that you used the string builder to build a string that contains all the information from the ListView, and not just a single row in the view. Then you put it all in the database.
The solution is to insert into the database one at a time.
how to get row value on every time
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
StringBuilder sb3 = new StringBuilder();
for(int i=0; i<simpleAdapter.getCount(); i++) {
String a = ((TextView) findViewById(R.id.al)).getText().toString();
String b = ((TextView) findViewById(R.id.sh)).getText().toString();
String c = ((TextView) findViewById(R.id.acc)).getText().toString();
simpleAdapter.getItem(i).toString();
sb.append(a);
sb.append("\n");
sb2.append(b);
sb2.append("\n");
sb3.append(c);
sb3.append("\n");
String text = sb.toString();
String text2 = sb2.toString();
String text3 = sb3.toString();
}}

How to add to an ArrayList the data of a ResultSet?

I want to have an ArrayList with the data that is in a PostgreSQL database.
For example:
Column1 Column2 Column3 Column4
A B C D
J D S E
arraylist.get(0) = (A, B, C, D)
arraylist.get(1) = (J, D, S, E)
I have this:
public static ArrayList<Ordenes> SelectInstruct (int a) throws SQLException
{
String driver = "org.postgresql.Driver";
String server = "jdbc:postgresql://localhost:5432/postgres";
String user = "usuario";
String pass = "contraseƱa";
ArrayList<Ordenes> ordenes = new ArrayList<Ordenes>();
Ordenes ord = new Ordenes();
try
{
Class.forName(driver);
Connection conexion = DriverManager.getConnection(server, user, pass);
Statement dato = conexion.createStatement();
ResultSet rs = dato.executeQuery("SELECT * FROM \"Ordenes\"" + "WHERE \"Operario\" = "+a+";");
conexion.close();
rs.
if (rs.next())
{
ord.setNumOrden(rs.getString("Numero de orden"));
ord.setStatus(rs.getString("Status"));
ord.setFechaInicio(rs.getString("Fecha Inicio"));
ord.getPrd().setNumero(rs.getInt("Numero de producto"));
ord.getPrd().setDescripcion(rs.getString("Descripcion Producto"));
ord.setCantidad(rs.getInt("Cantidad Solicitada"));
ord.setDescripcion(rs.getString("Descripcion Orden"));
ord.getPrd().getInstr().get(0).setCodIns(rs.getInt("Codigo Instruccion"));
ord.getPrd().getInstr().get(0).setMat(rs.getInt("Material"));
ord.getOper().add(rs.getInt("Operario"));
}
ordenes.add(ord);
}
catch (Exception e)
{
}
return ordenes;
}
Can I insert a While or a For?
If you excepting more result the use while loop like below code. I change only if to while.
public static ArrayList<Ordenes> SelectInstruct (int a) throws SQLException
{
String driver = "org.postgresql.Driver";
String server = "jdbc:postgresql://localhost:5432/postgres";
String user = "usuario";
String pass = "contraseƱa";
ArrayList<Ordenes> ordenes = new ArrayList<Ordenes>();
try
{
Class.forName(driver);
Connection conexion = DriverManager.getConnection(server, user, pass);
Statement dato = conexion.createStatement();
ResultSet rs = dato.executeQuery("SELECT * FROM \"Ordenes\"" + "WHERE \"Operario\" = "+a+";");
conexion.close();
rs.
while(rs.next())
{
Ordenes ord = new Ordenes();
ord.setNumOrden(rs.getString("Numero de orden"));
ord.setStatus(rs.getString("Status"));
ord.setFechaInicio(rs.getString("Fecha Inicio"));
ord.getPrd().setNumero(rs.getInt("Numero de producto"));
ord.getPrd().setDescripcion(rs.getString("Descripcion Producto"));
ord.setCantidad(rs.getInt("Cantidad Solicitada"));
ord.setDescripcion(rs.getString("Descripcion Orden"));
ord.getPrd().getInstr().get(0).setCodIns(rs.getInt("Codigo Instruccion"));
ord.getPrd().getInstr().get(0).setMat(rs.getInt("Material"));
ord.getOper().add(rs.getInt("Operario"));
}
ordenes.add(ord);
}
catch (Exception e)
{
// handle the exception here
}
return ordenes;
}
I suggest you to create a List of Lists.
List<List<String>> contents = new ArrayList<List<String>>();
for(int i = 0; i < 10; i++)
{
List<String> columns = new ArrayList<String>();
for(int j = 0; j < 4; j ++)
{
columns.add(j + "");
}
contents.add(columns);
}
System.out.println(contents.get(0));
Output
[0, 1, 2, 3]
Applying this to your problem
List<List<String>> contents = new ArrayList<List<String>>();
while(rs.next())
{
List<String> columnData = new ArrayList<String>();
columnData.add(rs.getString("name"));
columnData.add(rs.getString("email"));
columnData.add(rs.getString("phone"));
columnData.add(rs.getString("fax");
//Add all your data to the contents ArrayList
contents.add(columns);
}
System.out.println(contents.get(0));

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException UNKNOWN COLUMN

I am currently trying to scan and parse the file that is not in sql format. I am trying to input all the data into the SQL table but for some reason every time i run the program, i get the error saying unknown column 'what' in 'field list.' So the neither of the data goes through. 'what' is one of the names that is on the text. The table currently has 11 columns. I know I am parsing or scanning it wrong but I cannot figure out where. Here is my code:
public class parseTable {
public parseTable (String name) throws FileNotFoundException
{
File file = new File(name);
parse(file);
}
private void parse(File file) throws FileNotFoundException
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/";
String connectionUser = "";
String connectionPassword = "";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
String query = "";
for(int i = 0; i < rowInfo.length; i++)
{
if(query.equals(""))
{
query = rowInfo[i];
}
else if(i == 9){
query = query + "," + rowInfo[i];
}
else if(rowInfo[i].equals(null)){
query = query + ", " + "NULL";
}
else
query = query + ", " + "'" + rowInfo[i] + "'";
}
stmt.executeUpdate("INSERT INTO dup VALUES(" + query + ")");
count = 0;
rowInfo = new String[11];
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
And this is the data I'm trying to input:
1 hello cheese 1111 what#yahoo.com user adm street zip what USA
2 Alex cheese 1111 what#yahoo.com user adm street zip what USA
So this is my new code now, using PrepareStatement. However I still get an error and I looked online for the solution on where I'm making a mistake, but I cant seem to figure out where.
String query = "INSERT INTO mil_table (UserName, NameFirst, NameLast, supportID, EmailAddress, Password,
IDQ, AddressCity, AddressState, AddressZip, AddressCountry) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(query);
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
for(int i = 0; i <rowInfo.length; i++)
{
pstmt.setString(i + 1, rowInfo[i]);
}
//stmt.executeUpdate("INSERT INTO mil_table VALUES(" + query + ")");
//System.out.println("#" + query + "#");
pstmt.executeUpdate();
count = 0;
rowInfo = new String[11];
}
}
As you are using MySQL, you will need to enclose the text inputs with quotes. Try enclosing the String values that you are inserting in quotes and then execute your code.

How to paint an image in Jtable with Mysql

Hello I would like to print data from mysql query to my Jtable, I knw how to print the conventional data(String), but do not know how to do it with pictures. What I need is print the picture in the first cell of the table.
public void SearchMovie() throws SQLException {
try {
Connection con = null;
ResultSet rs = null;
Statement st = null;
String Genre = ComboGenero.getSelectedItem().toString();
String Era = ComboEra.getSelectedItem().toString();
String Clsssification = ComboClasification.getSelectedItem().toString();
String sql = "select Foto,Title,Year,Country ,Rating from movie where Genre ='" + Genre + "'";
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/whichmovie", "Asis", "dekrayat24");
st = con.createStatement();
rs = st.executeQuery(sql);
DefaultTableModel model = new DefaultTableModel();
this.jTable1.setModel(model);
jTable1.setDefaultRenderer(Object.class,new IconCellRenderer());
jTable1.setRowHeight(40);
ResultSetMetaData rsMD = rs.getMetaData();
int numcolumnas = rsMD.getColumnCount();
for (int x = 1; x <= numcolumnas; x++) {
model.addColumn(rsMD.getColumnLabel(x));
}
while (rs.next()) {
Object[] fila = new Object[numcolumnas];
for (int i = 0; i < numcolumnas; i++) {
fila[i] = rs.getObject(i + 1);
ResultadosLabel.setText(numcolumnas + "Movies found");
}
model.addRow(fila);
}
rs.close();
st.close();
con.close();
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
Thanks .

deleterow() ReadOnly Statement error

i'm doing my first applications using JDBC/Oracle...
Today i had a problem and i can't find out what's wrong.
That's my code (some parts)
My global variables:
public class Esercizio02_GestioneDB {
public Esercizio02_GestioneDB(){
}
public Connection conn = null;
public Statement s = null;
public ResultSet rs = null;
public ResultSet rs1 = null;
ResultSetMetaData rsmd = null;
ResultSetMetaData rsmd1 = null;
[...]
My connection method:
public void connetti(String user, String pwd) throws ClassNotFoundException, SQLException {
//DRIVER
Class.forName("oracle.jdbc.driver.OracleDriver");
//URL
String url = "jdbc:oracle:thin:#//localhost:1521/xe";
//CONNECTION
conn = DriverManager.getConnection(url, user, pwd);
//AUTOCOMMIT
conn.setAutoCommit(true);
//STATEMENT
s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
}
So, i have a method to delete a row in a table:
private void eliminaPrenotazione() {
try {
String message1 = "Scegli la prenotazione da cancellare:\n\n";
String query = "SELECT * FROM camere_prenotate";
rs1 = s.executeQuery(query);
rsmd1 = rs1.getMetaData();
message1 += "INDICE ";
for (int i=1; i<=rsmd1.getColumnCount(); i++) {
message1 += rsmd1.getColumnName(i);
message1 += " \t ";
}
message1 += "\n_______________________________\n";
int rowIndex = 1;
String columnType = "";
while (rs1.next()) {
message1 += "["+rowIndex+"]. ";
rowIndex++;
for (int i=1; i<=rsmd1.getColumnCount(); i++) {
columnType = rsmd1.getColumnTypeName(i);
if(columnType.substring(0, 3).equalsIgnoreCase("num")) message1 += rs1.getInt(i);
if(columnType.substring(0, 3).equalsIgnoreCase("var") || columnType.substring(0, 3).equalsIgnoreCase("dat"))
message1 += rs1.getString(i);
message1 += " \t ";
}
message1 +="\n";
}
message1 +="\n";
String scelta = JOptionPane.showInputDialog(null, message1);
int sceltaInt = Integer.parseInt(scelta);
rs1.absolute(sceltaInt);
rs1.deleteRow();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Errore: " + e.getMessage());
}
}
deleteRow() returns me an error... it says me that my ResultSet is read only, but in my statement it's delcared as
s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
so, what's wrong?
sry for the noobish code and the bad english -.-'''
select * makes the Resultset instance readonly.
select COLUMNNAME makes it updatable.

Categories

Resources