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();
}}
Related
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);
}
}
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.
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.
I have a problem regarding my JTable, I don't know how can I store my fetch records which is of type String from my database to the multidimensional array which is let's say Object[][] data. What I want to do is show my database records to the JTable, I already fetch the records in dtabase and store it in my String variables, The question is how can I store the fetch records to the multidimensional array of Object and use it on my JTable.
Here are my code for fetching records:
static class TableData{
Object[][] data;
int count = 0;
Statement sql = null;
String query, user = "JEROME", pass = "Perbert101", driver = "oracle.jdbc.OracleDriver", conString = "jdbc:oracle:thin:#127.0.0.1:1521:XE";
Connection con = null;
ResultSet rs = null;
TableData(){
try{
Class.forName(driver);
}
catch(ClassNotFoundException e){
JOptionPane.showMessageDialog(null, "Problem Loading Driver");
}
try{
con = DriverManager.getConnection(conString, user, pass);
sql = con.createStatement();
sql.executeQuery("SELECT * FROM INVENTORY");
rs = sql.getResultSet();
int key = 0;
String val = null, val1 = null, val2 = null, val3 = null, val4 = null, val5 = null;
System.out.println("Results: ");
while(rs.next()){
key = rs.getInt(1);
if(rs.wasNull()){
key = -1;
}
val = rs.getString(2);
if(rs.wasNull()){
val = null;
}
val1 = rs.getString(3);
if(rs.wasNull()){
val = null;
}
val2 = rs.getString(4);
if(rs.wasNull()){
val = null;
}
val3 = rs.getString(5);
if(rs.wasNull()){
val = null;
}
val4 = rs.getString(6);
if(rs.wasNull()){
val = null;
}
val5 = rs.getString(7);
if(rs.wasNull()){
val = null;
}
System.out.println("Key = " + key);
System.out.println("value = " + val);
System.out.println("value = " + val1);
System.out.println("value = " + val2);
System.out.println("value = " + val3);
System.out.println("value = " + val4);
System.out.println("value = " + val5);
}
sql.close();
con.close();
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, "Error Loading Database Data");
}
}
}
//----------END------------
public static void main(String[] args){
POSModel.TableData data = new POSModel.TableData();
}
I'd suggest that the data you're pulling from the database needs to be stored in an array (by columns) first...
Object[] rowData = new Object[7];
rowData[0] = key;
rowData[1] = val;
rowData[2] = val1;
rowData[3] = val2;
rowData[4] = val3;
rowData[5] = val4;
rowData[6] = val5;
This then needs to be stored in some kind of row structure, I'd personally use a List. The main reason for this choice is that you probably don't know in advance the number of rows you will be reading...
List<Object[]> rowList = new ArrayList<Object[]>(25);
// Process the resultset...
// Create the column array from above...
rowList.add(rowData);
Once you've completed reading all the rows, you need to convert the list it an array...
data = rowList.toArray(new Object[](rowList.size())); // I like to provide my own array
Equally, you could do...
data = new Object[rowList.size()][7];
rowList.toArray(data);
Which ever is more convenient...
Now you should have a 2D array...
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.