I have some trouble removing specific users from my SQLite database on my Android device. I made a simple method to delete a table row where table.name equals first input and table.surname equals second input.
Here is my method:
void deleteUser(db_operations opt, String name, String surname) {
SQLiteDatabase sdb = opt.getWritableDatabase();
if(validate(name, surname) == true) {
name = name.replaceAll("\\s+",""); surname = surname.replaceAll("\\s+","");
try {
String DELETE_USER = "DELETE FROM " + tb_users.tb_name + " WHERE " + tb_users.name + "='" + name + "' AND " + tb_users.surname + "='" + surname + "'";
sdb.execSQL(DELETE_USER);
sdb.close();
System.out.println("Deletion SUCCESS!");
} catch (SQLException e) {
System.out.println("Deletion FAILED!");
}
}
}
If I execute a DELETE FROM myTableName statement, every user is removed from the table and from my ScrollView which is ok, but if I execute the above method to remove a specific user, output gives:
Deletion SUCCESS!
but my table still has the record. The record also remains in my ScrollView list (made with LinearLayouts). The list is built dynamically. I've already checked if the data is good or not before my SQLite execution starts and it looks ok. I can't figure out why my method doesn't work. Maybe I've missed something.
(Posted on behalf of the question author).
I got it working. I found out that my validation method was returning false output all the time (I made a typo in one of the conditions), that's why my method never got a chance to execute. Thanks for a reminder to use logs. Was able to track my typo.
I came across a problem with going through a ResultSet I'm generating from my MySQL db. My query should return at most one row per table (I'm looping through several tables searching by employee number). I've entered data in some of the tables; but my test o/p says that the resultset contains 0 rows and doesn't go through the ResultSet at all. The o/p line it's supposed to print never appears. It was in a while loop before I realised that it'd be returning at most one row, at which point I just swapped the while(rs.next()) for an if(rs.first()). Still no luck. Any suggestions?
My code looks like this:
try
{
rsTablesList = stmt.executeQuery("show tables;");
while(rsTablesList.next())
{
String tableName = rsTablesList.getString(1);
//checking if that table is a non-event table; loop is skipped in such a case
if(tableName.equalsIgnoreCase("emp"))
{
System.out.println("NOT IN EMP");
continue;
}
System.out.println("i'm in " + tableName); //tells us which table we're in
int checkEmpno = Integer.parseInt(empNoLbl.getText()); //search key
Statement s = con.createStatement();
query = "select 'eventname','lastrenewaldate', 'expdate' from " + tableName + " where 'empno'=" + checkEmpno + ";"; // eventname,
System.out.println("query is \n\t" + query + "");
rsEventDetails = s.executeQuery(query) ;
System.out.println("query executed\n");
//next two lines for the number of rows
rsEventDetails.last();
System.out.println("no. of rows is " + rsEventDetails.getRow()+ "\n\n");
if(rsEventDetails.first())
{
System.out.println("inside the if");
// i will add the row now
System.out.println("i will add the row now");
// cdTableModel.addRow(new Object[] {evtname,lastRenewalDate,expiryDate});
}
}
}
My output looks like this:
I'm in crm
query is
select 'eventname','lastrenewaldate', 'expdate' from crm where 'empno'=17;
query executed
no. of rows is 0
I'm in dgr
query is
select 'eventname','lastrenewaldate', 'expdate' from dgr where 'empno'=17;
query executed
no. of rows is 0
NOT IN EMP
I'm in eng_prof
query is
select 'eventname','lastrenewaldate', 'expdate' from eng_prof where 'empno'=17;
query executed
no. of rows is 0
I'm in frtol
query is
select 'eventname','lastrenewaldate', 'expdate' from frtol where 'empno'=17;
query executed
no. of rows is 0
(and so on, upto 17 tables.)
The '17' in the query is the empno that I've pulled from the user.
The thing is that I've already entered data in the first two tables, crm and dgr. The same query in the command line interface works; this morning, I tried the program out and it returned data for the one table that had data in it (crm). The next time onwards, nothing.
Context: I'm working on a school project to create some software for my dad's office, it'll help them organise the training etc schedules for the employees. (a little like Google Calendar I guess.) I'm using Netbeans and Mysql on Linux Mint. There are about 17 tables in the database. The user selects an employee name and the program searches for all entries in the database that correspond to an 'event' (my generic name for a test/training/other required event) and puts them into a JTable.
The single quotes around the column names and table name in the creation of the query seem to have caused the problem. On changing them to backticks, retrieval works fine and the data comes in as expected.
Thank you, #juergend (especially for the nice explanation) and #nailgun!
i am a beginner in java Desktop application, and i was trying to insert some data into my table and i get the following reply "colown count does not match value count at row 1" here is my query
String sql = "insert into cataloguetb(title_statement,aurthurs_name,edition_statement,book_title,publisher_name"
+ "place_of_publication,year_of_publication,isbn_no,index_no,pagenRomannuem,pagneArabi,illuss,size_of_book"
+ "otherAurthurs,addEntries,length_in_cm,accessionNO,call_No1,call_No2,call_No,call_No4)values ('"+(titleStatement)+"','"+(aurthursName)+"'"
+ "'"+(editionStatement)+"','"+(bookTitle)+"','"+(publisherName)+"','"+(placeOfPublication)+"','"+(yearOfPublication)+"'"
+ "'"+(isbnNo)+"','"+(indexNo)+"','"+(pageRoman)+"','"+(pageArabic)+"','"+(illustration)+"','"+(size)+"','"+(otherAuthurs)+"'"
+ "'"+(addedEntries)+"','"+(lengthOfBook)+"','"+(accessionNo)+"','"+(calNo1)+"','"+(calNo2)+"','"+(calNo3)+"','"+(calNo4)+"')";
i have tried so many solutions even from stacflowoverflow there seem to no solution thanks for your help.
You need trailing commas on the fields at the end of the rows. Try this:
String sql = "insert into cataloguetb(title_statement,aurthurs_name,edition_statement,book_title,publisher_name,"
+ "place_of_publication,year_of_publication,isbn_no,index_no,pagenRomannuem,pagneArabi,illuss,size_of_book,"
+ "otherAurthurs,addEntries,length_in_cm,accessionNO,call_No1,call_No2,call_No,call_No4) values ('"+(titleStatement)+ "','"+(aurthursName)+"',"
+ "'"+(editionStatement)+"','"+(bookTitle)+"','"+(publisherName)+"','"+(placeOfPublication)+"','"+(yearOfPublication)+"',"
+ "'"+(isbnNo)+"','"+(indexNo)+"','"+(pageRoman)+"','"+(pageArabic)+"','"+(illustration)+"','"+(size)+"','"+(otherAuthurs)+"',"
+ "'"+(addedEntries)+"','"+(lengthOfBook)+"','"+(accessionNo)+"','"+(calNo1)+"','"+(calNo2)+"','"+(calNo3)+"','"+(calNo4)+"')";
This is because number of columns that you want to enter and datas(values for columns) you are entering are not same
the output of your code will be something like this
insert into cataloguetb(title_statement,aurthurs_name,edition_statement,book_title,publisher_nameplace_of_publication,year_of_publication,isbn_no,index_no,pagenRomannuem,pagneArabi,illuss,size_of_bookotherAurthurs,addEntries,length_in_cm,accessionNO,call_No1,call_No2,call_No,call_No4)values (.......)
That means you trying to insert in 19 columns but giving 21 values.So the error.
Well it is not the proper way of insertion.
Better would be to use PreparedStatement like this way
PreparedStatement pt=con.prepareStatement("insert into table (x,y) values(?,?");
pt.setString(1,value_for_x);
pt.setString(2,value_for_y);
pt.executeUpdate();
Here is a method which displays Jobs from SQlite onto a table and sets them as labelText appropriately.
private void setLabelText() {
try {
String table_click0 = (table_job.getModel().getValueAt(row, 0).toString());
String sqlSt = "SELECT Employer.name, * FROM Job INNER JOIN Employer ON Job.employerID = Employer.employerID WHERE jobID='"+table_click0+"' ";
conn = JavaConnect.ConnectDB();
pst = conn.prepareStatement(sqlSt);
rs = pst.executeQuery();
if(rs.next()) {
descriptionArea.setText(rs.getString(5));
empTitLabel.setText(rs.getString(1)+" - "+rs.getString(4));
idLabel.setText("Job Reference: " + rs.getString(2));
typeLabel.setText("Job Type: " + rs.getString(6));
salaryLabel.setText("Salary: " + rs.getString(7));
benefitsLabel.setText("Benefits : " + rs.getString(8));
vacLabel.setText("Vacancies : " + rs.getString(9));
closeLabel.setText("Closing Date: " + rs.getString(10));
reqLabel.setText("Requirement : " + rs.getString(11));
placeLabel.setText("Placement : " + rs.getString(12));
applyToLabel.setText("Apply To: " + rs.getString(13));
statusLabel.setText("Job Status: "+rs.getString(14));
locLabel.setText("Location: "+rs.getString(16));
postedLabel.setText("Posted: "+rs.getString(15));
}
}
I want to be able to now allow users to select the Job (clicked row on table) to allow editing for update of data. So i provide a form to do that, instead of repeating lines such as descriptionArea.setText(rs.getString(5)); for Form textfields, is there a shorter way of doing this. or does each JTextfield have to be individually manipulated using textfieldName.setText(....) way, is there any tricks to do it shorter? any nice easy techniques to perhaps reuse the above code to minimise repetition.
You might want to look at the Apache Commons DbUtils, which uses Class Literals as Runtime-Type Tokens and ResultSetMetaData to simplify some of the more tedious parts of JDBC.
Despite JTextField being for editing you could use for displaying your results. You could change to editable whenever clicked.
I have the following problem:
I have two tables in one data base which consist of the same columns besides the name of the last column. I want to write data into them using Java.
I want to use the same preparedStatement for both tables, where I check with an if-command whether it is table1 or table2. table2 has amount10 as the name for the last column, table1 has amount20 for it. This number is stored in a variable within my code.
Below you can see a (simplified) example and how I tried to let the column name variable but it doesn't work. Is there any way to fix this without copying the whole statement and manually changing the number variable?
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount`+"number") VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount`+"number" = ? ; ";
PreparedStatement insertDataStmt;
This will not work since variables number and table are not going to be magically injected into your insertData string while you are changing them.
I'd to a method prepareInsertstatement(String table, String number) that would return correct PreparedStatement:
public void prepareInsertStatement(Connection conn, Strint table, String number) {
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount+"number"') VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount+"number"' = ? ; ";
PreparedStatement insertDataStmt = conn.prepareStatement(insertData);
return insertDataStmt;
}
Just remember to close the PreparesStatement when you don't need it any more.
I suppose that reason for that is invalid syntax. When you concatenate string for last column name you use code 'amount' + number. If your number value is 20, than concat result will be
'amount'20 that cause invalid syntax exception. Just move one extra ' after number.
"'amount" + number + "'"
Note: log, or just error that appears during this statement execution would be very useful to find right answer for your question.