Writing multiple where clauses in Java using Mysql - java

below is code is a code i wrote to get the value of 'monthly Depreciation' when i select the row on my j Table by either mouse-clicked or key-pressed. but it only selects the first value for 'monthly depreciation' when i click on the rows or key-press.the problem i know is coming from the where statement but can't seem to get around it.
if(evt.getKeyCode()==KeyEvent.VK_DOWN || evt.getKeyCode()==KeyEvent.VK_UP)
{
try{
int row =dep_report.getSelectedRow();
String Table_click=(dep_report.getModel().getValueAt(row, 0).toString());
String sql ="select Date_Acquired 'Date Acquired',Serial_Number 'Serial Number',"
+ " Description 'Description',Cost_Of_Acquisition 'Cost Of Acquisition',"
+ "Monthly_Depreciation 'Monthly Depreciation',Accumulated_Depreciation 'Accumulated Depreciation',Net_Book_Value 'Net Book Value'"
+ ",asset_update.Branch_Area 'Branch Area',Depts_name 'Department Name' ,User 'User',"
+ "Status 'Status' from items,asset_update where items.items_No = asset_update.items_No &&'"+Table_click+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()){
String add1 = rs.getString("Monthly Depreciation");
MonthlyDep.setText(add1);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
I would really appreciate the help thank you.

In your sql
where items.items_No = asset_update.items_No &&'"+Table_click+"'";
&& wont work for sql and you might need
where items.items_No = asset_update.items_No and items.someThing= '"+Table_click+"'";

Please use Java naming conventions and give proper names to things Table_click is a horrible variable name.
But can you describe what is in your table model in the 1st column of the selected row?
You seem to append that to your query and if it does not contain a valid SQL part, this will not work well with your statement. In a where clause you usually check a column against a value. I doubt that your table model has this written there, more likely you just have the value in your table model at this position.
Also make sure to properly use prepared statements. Never put the values directly in the SQL string you create or you create the perfect entry point for SQL injection. Assign the values instead once you have created the statement with something like this: pst.setString(1, Table_click);

Related

My query is giving following error,Unexpected token WHERE

i'm working in java with sql.when ever this query is executed it gives me the error mentioned in title
try(PreparedStatement statement = conn.prepareStatement("INSERT INTO student_signup(q" + strId + ")" + "WHERE student_email="+email+"VALUES(?)")) {
statement.setString(1, SelectedOption);
statement.executeUpdate();
statement.close();
for a little code background
here
int questionID=1;
String strId = Integer.toString(questionID);
String email = signInForm.getTxtEmail().getText();
INSERT inserts new rows. I think you want to change a value in an existing row. For that, use UPDATE. Something like this:
UPDATE student_signup
SET strID = ?
WHERE student_email = ?;
INSERT is never use with WHERE clause
If you want to change the value for a pre-existing record in the database, you should try the UPDATE clause with WHERE condition after it.

Insert new Value in MySQL in same Cloumn (Java/Code)

I am working on a little project.
Now I don't know, how to "replace" a old value in the mysql table.
Here you can see the table:
Thats my methods:
MySQL.update("INSERT INTO OnlineServer (Name) VALUES ('" + API.getServerFreeServer() + "');");
public static void update(String qry) {
try {
java.sql.Statement st = con.createStatement();
st.executeUpdate(qry);
st.close();
} catch (SQLException e) {
connect();
e.printStackTrace();
}
}
The problem now is, if I update the mysql, it dont replace the value in the column "Name". It just add a new Value under the old Value. The table is Going to be too huge if I Update every 5 seconds.
I need exactly one value in the column "Name".
So I have tryed to replace the insert but it doesn't work for me.
Maybe you have some ideas?
Sorry for my bad English, I'am German.
It sounds like you want to do an update here of the table, rather than an insert:
String sql = "UPDATE OnlineServer Set Name = ?";
PreparedStatement ps = dbConnection.prepareStatement(sql);
ps.setString(1, API.getServerFreeServer());
ps.executeUpdate();
By the way, your current query is doing raw string concatenation, making it prone to typos as well as SQL injection. I have used a prepared statement above, which is the most desirable way to execute a query using JDBC.
INSERT operation is for adding new record only and thus irrespective of you specify single column or 1million column it will add a new record. You actually need an UPDATE statement saying
UPDTE OnlineServer SET Name = <value>
You might also want to check INSERT ... ON DUPLICATE KEY UPDATE

How to import text longer than String from JTextArea into TEXT field in database

I have a problem with this for a while. Importing data from TEXT field into textArea make no problem for me (even if it's longer than String), but I have no idea how to make it work opposite way. (Using sqlite)
My code to get data from db:
Statement myStmt = con.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * from test");
while(myRs.next())
{
if(myRs.getInt("Id_przepisu") == przepis.getId_przepisu() )
{
textArea.setText(myRs.getString("text"));
}
}
myStmt.close();
myRs.close();
code to save data in db
insert = con.prepareStatement
( "INSERT INTO test (Id_przepisu, text) VALUES ('"+przepis.getId_przepisu()+"','"+
textArea.getText()+"')");
insert.executeUpdate();
You might find a good answer and workaround for you problem here: https://stackoverflow.com/a/17785119/575643
In short, if is bigger than the TEXT type you would need to split it manually. Search for substring, it would help.

Postgresql with java: query produced no result after insert

I write a little program to admin my video collection.
/*
insert new data set into the table
*/
int next = 0;
rs = st.executeQuery("Select max(category_id) from category;");
if (rs.next()) {
next = rs.getInt(1) + 1;
System.out.println(next);
}
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
rs = st.executeQuery(query);
//on this place is the exception thrown
// this will not execute anymore
rs = st.executeQuery("DELETE FROM category WHERE name = 'Mystics';");
The program can select on tables, make joins but insert make trouble.
I try to insert some new data in my table (see Java-code). After the second test the output show me that the data was inserted. But after Insert was an exception thrown.
1 & 2 are the tests from yesterday and today. (3) was inserted but not selected yet.
1 Mystics 2015-07-05
2 Mystics 2015-07-06
3
org.postgresql.util.PSQLException: query produced no result.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:287)
at postgre_java.Zetcode.main(Zetcode.java:55)
do you have some advises for me?
Do not manipulate data with read statements!
If you want to insert, update, delete data in db use
Statement stmt = conn.createStatement();
stmt.executeUpdate(SQL);
executeQuery returns resultset, but all that INSERT, UPDATE, DELETE can return is number of affected rows and that is what executeUpdate is returning.
And never, never, never*100 use string concatenation in SQL use Prepared statements!
In Java, you use executeQuery for a SELECT statement or some other statement which returns something. If you want to execute an INSERT, UPDATE or DELETE without returning something, you should use executeUpdate().
Statement#executeUpdate() is meant for that purpose
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
int noOfRows= st.executeQuery(query)
but it doesnt return a ResultSet , rather the no of rows affected that you could store into an Integer
Also your is highly vulnerable to Sql injection , try using the PreparedStatements to safeguard your code

JDBC: Create Table with PreparedStatement, SQL Syntax Error or not?

I am encountering some difficulties trying to, in a dynamic way, create a new table using PreparedStatement. I am trying to add a unknown number of columns and their respective types and sizes. I keep getting SQL Syntax errors, but I suspect this may not be the case here.
Variables used:
con = Connection object
colNames = String[] containing column names ("person", "email" etc)
colTypes = String[] containing column types ("varchar", "int" etc)
colSizes = String[] containing column sizes ("100", "11", etc)
Should be pretty self-explanatory.
con.setAutoCommit(false);
String sql = "? ?(?),";
PreparedStatement ps = con.prepareStatement(sql);
ps.addBatch("create table " + tablename + "( ");
for (int i = 0; i < colNames.length; i++){
if (!(i == colNames.length-1)) {
ps.setString(1, colNames[i]);
ps.setString(2, colTypes[i]);
ps.setString(3, colSizes[i]);
} else {
String format = "%s %s(%s)";
String lastLine = String.format(format, colNames[i], colTypes[i], colSizes[i]);
ps.addBatch(lastLine);
}
}
ps.addBatch(");");
ps.executeBatch();
NOTE: Yes, this is homework. I don't want any dead giveaways, rather pointers as to in what way I am misusing some functions, which I suspect.
Best regards,
Krys
You need to give the full SQL statement to addBatch. It is not a tool to construct a dynamic SQL statement. It is a tool to improve performance when running multiple statements. You don't need it here.
You also don't need a PreparedStatement here, as you are not going to have bind variables (i.e. column data as opposed to column names) and are not going to run the same SQL repeatedly (but it does not hurt, either). setString and friends do not work for column or table names, just for data.
A StringBuilder is a good tool to construct a String with variable parts.

Categories