I have a window that displays my data based on data in a table, but the trouble is that when I change and I click on the save button I get an error : Error:No value specified for parameter 1.
But I do not want to change all columns just the latest
enregistrer.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
String sql = null;
try {
if(col==4)
sql = "UPDATE impaye" + "SET Impayé = ?" + "WHERE ID = ? "+ row;
preStat =(PreparedStatement) connexion.prepareStatement(sql);
preStat.setObject(1, table.getValueAt(row, col));
preStat.executeUpdate();
preStat.close();
} catch (SQLException insertException) {
System.out.println("Error:"+insertException.getMessage());
}
}
});
But I do not want to change all columns just the latest
Well then you need to change your SQL. Currently your SQL updates all 4 columns.
If you only want to update a single column, then you need 4 SQL statements. The statement you use will be based on the index of the column that was changed.
Something like:
String sql = null;
if (col == 0)
sql = "UPDATE impaye SET Date = ? " + row;
else if (col == 1)
sql = "UPDATE impaye SET Débiteur = ? " + row);
else if
...
preStat =(PreparedStatement) connexion.prepareStatement(sql);
preStat.setObject(1, table.getValueAt(row, col));
preStat.executeUpdate();
I think you will also need a "where" clause in your SQL. I don't think you can just specify a row number (but I don't know much about SQL).
Related
I am developing a software in Java, what I am doing is searching a value in full sqlite database (55 Columns and 1000 rows) and updating it.
I can find that value in the database but when I am try to update it I want to skip columns which have only NULL values. Using ResultSet it automatically skips other columns which have non-null values.
How can I check if ResultSet is not skipping the columns, finding the desired column and updating that value?
What I tried is:
ArrayList<String> arr = new ArrayList<String>() ;
rs = statement.executeQuery(); // that is the select statement
//Select * FROM table_name WHERE column1 like %VALUE%' OR column2 like %VALUE% and other columns like this too...
List<String> cols = Arrays.asList(getColLabels());
// I am getting Column Labels from ResultSetMetaData and it works fine
while(rs.next()){
for(String column: cols){
String value;
if(rs.getBoolean(column)){
//That is the problematic area, if ResultSet finds a column with full of NULL values it skips to next column.
// But other columns it skips too , which have not null Values and after that ResultSet does not find a proper column.
if((value = rs.getObject(column).toString()).matches(".*"+searchedVal+".*") ){
//searchedVal is searched value
arr.add("UPDATE Table_Name SET "+column+" ='"+newValue+"' WHERE "+ column+" ='" +value+"';" );
// then send array in another function to update to database
break;
}
}
}
}
Thank you for your help.
Please try to solve the problematic area with the data tier(SQL command), not the business trie(java code).
You want to have rows which all of the columns must be non null? so simply add more condition clauses(not null) to your sql command
something like:
Select * FROM table_name WHERE column1 like %VALUE%' OR column2 like %VALUE% and column_n like %VALUE% and (column1 not null and column2 not null and column_n not null)
I found the answer,
rs.getBoolean does not work with different type of column types, so I changed getObject function.
Working code is:
ArrayList<String> arr = new ArrayList<String>() ;
rs = statement.executeQuery(); // that is the select statement
//Select * FROM table_name WHERE column1 like %VALUE%' OR column2 like %VALUE% and other columns like this too...
List<String> cols = Arrays.asList(getColLabels());
// I am getting Column Labels from ResultSetMetaData and it works fine
while(rs.next()){
for(String column: cols){
String value;
if(rs.getObject(column) != null){
if((value = rs.getObject(column).toString()).matches(".*"+searchedVal+".*") ){
//searchedVal is searched value
arr.add("UPDATE Table_Name SET "+column+" ='"+newValue+"' WHERE "+ column+" ='" +value+"';" );
// then send array in another function to update to database
break;
}
}
}
}
I keep getting android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 exception when trying to get a single row from a Sqlite table using a ID value.
Why do you think this happens? What is wrong with my code?
public Product getProduct(DBOps dop, String productId) {
Product p = new Product();
String sqlQuery = "SELECT " + TableInfo.PID + " FROM "
+ TableInfo.TABLE_NAME +" WHERE pid="+"'"+productId+"'";
SQLiteDatabase SQ = dop.getReadableDatabase();
Cursor CR = SQ.rawQuery(sqlQuery, null);
try
{
if(CR.getCount() > 0)
{
while (!CR.isAfterLast()) {
p.PID = CR.getString(0);
p.NAME = CR.getString(1);
p.SIZE = CR.getString(2);
p.COLORS = CR.getString(3);
p.DESC = CR.getString(4);
p.PRICE= CR.getString(5);
p.OUTLETS = CR.getString(6);
p.FABRIC = CR.getString(7);
p.QUANTITY = CR.getString(8);
p.CATEGORY = CR.getString(9);
p.RATING = CR.getString(10);
CR.moveToNext();
}
}
else
{
CR.close();
}
}
catch(Exception ex)
{
Log.e("DBOps Error", "Look at DBOps Class's getProduct Method");
Log.e("DBOps Error", ex.toString());
}
return p;
}
android.database.CursorIndexOutOfBoundsException: Index -1 requested,
with a size of 1
Because you are currently selecting only one column from table which is TableInfo.PID but trying to retrieve more then one column from cursor.
So change select query by specify all columns in select query or use * FROM get all columns:
String sqlQuery = "SELECT * FROM "
+ TableInfo.TABLE_NAME +" WHERE pid="+"'"+productId+"'";
Use Like This
if(cursor.getCount()>0)
{
if(cursor.moveToFirst())
{ do
{
//your code
}
while(cursor.moveToNext());
cursor.close();
}
}
Hope it will helps u
You need to call cursor.moveToFirst() before using the cursor. This moves it to row 0. Make sure to check the return value- if it returns false then it could not move to row 0 for some reason (generally it means 0 rows returned).
So, i would like to retrieve database information where a user will search certain columns using text fields, like this:
column1 find userinput,
column2 find userinput,
column3 find userinput,
The problem im having is the sql statement:
String sql = "select * from table where column = '" + textfield1.getText() + "'";
If textfield1 is empty, it will only retrieve entries that contain nothing.
What im trying to retrieve will have 6 text field, meaning 6 columns in the database. Using java i would need alot of if statements.
Is there any other way to shorten this?
EDIT
-- MORE INFO --
The if statements will start from:
if (!(t1.getText().equals("")) && !(t2.getText().equals("")) && !(t3.getText().equals(""))
&& !(t4.getText().equals("")) && !(t5.getText().equals("")) && (t6.getText().equals("")))
all the way down to
if (t1.getText().equals("") && t2.getText().equals("") && t3.getText().equals("")
&& t4.getText().equals("") && t5.getText().equals("") && t6.getText().equals("")
covering all possible combinations of the 6 input fields, the point of all these statements is to ignore empty text fields but provide the corresponding sql statement.
I don't know how to calculate the possible combinations other than writing them all down(i started, there was too many).
I didn't really understand why those ifs, you should elaborate more your question but i will try to help as i can.
Well, if you want to retrieve everything from the database you could use LIKE:
String sql = "select * from table where column like '%" + textfield1.getText() + "%'";
This way you'll get everything with the containing text, it means, if the field is empty it will bring all results, i guess this is the best way to do, to avoid unnecessa if clauses.
Another thing, to check for empty fields you should use:
t1.getText().trim().isEmpty()
BUT if you let they write white spaces the LIKE won't help you then you need to .trim() all your texts then your white spaces will be ignored.
The following can be formulated much neater, but to make the point:
JTextField ts = new JTextField[6];
Set<String> values = new HashSet<>(); // Removes duplicates too.
for (JTextField t : ts) {
String text = ts.getText().trim();
if (!text.isEmpty()) {
values.add(text);
}
}
// Build the WHERE condition of a PreparedStatement
String condition = "";
for (String value : values) {
condition += condition.isEmpty() ? "WHERE" : " OR";
condition += " column = ?";
}
String sql = "select * from table " + condition;
PreparedStatement stm = connection.prepareStatement(sql);
int index = 1; // SQL counts from 1
for (String value : values) {
stm.setString(index, value);
++index;
}
ResultSet rs = stm.executeQuery();
The usage of a PreparedStatement makes escaping ' (and backslash and such) no longer needed and also prevents SQL injection (see wikipedia).
i have a problem i want to search data based on multiple jtext fields where did i go wrong coz this displays only one row which has the first id
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql="SELECT Employee.EmpID,Employee.Fname,Employee.Mname,Employee.Sname,Employee.DoB,Employee.Phone,"
+ "Employee.Email,Employee.Nationality,Employee.Desegnition,Employee.NSSF,Employee.WCF,"
+ "Employee.BSalary,Allowance.medical,Allowance.Bonus,Allowance.others,Allowance.tov,Allowance.TA,"
+ "Attendece.Hrs from Employee,Allowance,Attendece WHERE "
+ "Employee.EmpID=Allowance.EmpID and Attendece.EmpID=Allowance.EmpID AND Employee.EmpID=? AND Attendece.Dt=?";
try{
pd=conn.prepareStatement(sql);
pd.setString(1,id.getText());
pd.setString(2,Date1.getText());
r=pd.executeQuery();
//setting the text fields
if(r.next())
{
String a=r.getString("EmpID");
eid.setText(a);
String b=r.getString("Fname");
fname.setText(b);
String c=r.getString("Mname");
mname.setText(c);
String d=r.getString("Sname");
sname.setText(d);
String e=r.getString("DoB");
dob.setText(e);
String f=r.getString("Desegnition");
Des.setText(f);
String g=r.getString("Bsalary");
bsal.setText(g);
String h=r.getString("Phone");
phone.setText(h);
String i=r.getString("Email");
email.setText(i);
String j=r.getString("Nationality");
nationality.setText(j);
String k=r.getString("Desegnition");
Des.setText(k);
String l=r.getString("NSSf");
nssf.setText(l);
String m=r.getString("WCF");
wcf.setText(m);
String n=r.getString("tov");
oh.setText(n);
String o=r.getString("Bonus");
bn.setText(o);
String p=r.getString("medical");
md.setText(p);
String q=r.getString("others");
ot.setText(q);
String s=r.getString("TA");
ta.setText(s);
String t=r.getString("Hrs");
hrs.setText(t);
int day;
day=Integer.parseInt(t)/8;
days.setText(Integer.toString(day));
double week=day/7;
weeks.setText(Double.toString(week));
}
r.close();
pd.close();
}catch(Exception e)
{
}
I want to export data from A table and import the data to B table. A and B table are the same tables and they are have 100 columns. How can I export and import within JDBC? I want to do it dynamically. I do not want to write one column to other.(2 tables have same columns. But Table A in oracle and Table B in mysql)
Thank you.
Try:
insert into tableB
select * from tableA
This is possible also if the tables are in different databases, creating a DB-link between the databases (granted you have the permissions to do so).
You can otherwise copy a max number of columns from TableA in memory and than insert them into the TableB, but I strongly discourage this.
Unfortunately in java there is nothing similar to the .NET BulkCopy
This might be of help :
ResultSet rs = st.executeQuery("SELECT * FROM A");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
String insert_string = "INSERT INTO B(" ;
for (int i = 1; i < columnCount + 1; i++) {
String column = rsmd.getColumnName(i);
insert_string += column + ", " ;
}
insert_string += " )"; // Column part of INSERT INTO B should be well formed
insert_string += " VALUES (" ;
int i=0;
while(i < columnCount - 1){
i++;
insert_string += "'"+ rs.getString(i)+"', " ;
}
insert_string += "'" + rs.getString(columnCount) + ")" ; // VALUES part should be ok by now
This far, we must have a one valid INSERT statement, but that's only for one row in the rs object. An iteration with rs.next() must be included in the code so as to repead the creation of that INSERT string for all A rows.
As for the performance, I honestly have no clue. I don't recommend this, but I think it's a fair way of addressing the question.
How delete row from table with help jackcess?
I try so, but it's bad:
Table ptabl = db.getTable("person");
int pcount = ptabl.getRowCount();
for (int i = 0; i < pcount; i++) {
Map<String, Object> row2 = ptabl.getNextRow();
if (row2.get("id") == Integer.valueOf(1)) {
ptabl.deleteCurrentRow();
}
}
How set column "id" attribute to autoincrement?
Table newTable = new TableBuilder("diagnosis").
addColumn(new ColumnBuilder("id")
.setSQLType(Types.INTEGER)
.toColumn())
.addColumn(new ColumnBuilder("name")
.setSQLType(Types.VARCHAR)
.toColumn()).toTable(db);
If your id column is indexed, you can use an IndexCursor to quickly find columns:
IndexCursor cursor = new CursorBuilder(ptabl).setIndexByColumnNames("id").toIndexCursor();
if(cursor.findFirstRowByEntry(1)) {
cursor.deleteCurrentRow();
}
If your id column is not indexed, you can use a normal cursor, which is more convenient but effectively no faster than your current code (just does a table scan):
Cursor cursor = new CursorBuilder(ptab1).toCursor();
Column idCol = ptab1.getColumn("id");
if(cursor.findFirstRow(idCol, 1)) {
cursor.deleteCurrentRow();
}
And your own answer indicates you already figured out how to make a column auto increment.
For set autoincrement to column:
Table newTable = new TableBuilder("diagnosis").addColumn(new ColumnBuilder("id").setAutoNumber(true).setSQLType(Types.INTEGER).toColumn()).addColumn(new ColumnBuilder("name").setSQLType(Types.VARCHAR).toColumn()).toTable(db);