ok iam having a problem i need to delete all columns that start with ? on primery key ex.?5 ,?4 i amm running this throw a java app i have build so i need the java query that search my database ektupotiko and then delete all columns that start with ? on primary key
here is my try but it doesnt work any idea how i can make it work ?
public void mix(){
String queryy ="DELETE FROM ektupotiko WHERE Αριθμος_ΔΔΥ = ?% ");
executeSQLQueryy(queryy,"updated");
}
public void executeSQLQueryy (String queryy,String message) {
Connection con =getConnection();
Statement st;
try{
st =con.createStatement();
if((st.executeUpdate(queryy))==1)
{
con.commit();
// DefaultTableModel model=(DefaultTableModel)jTable_ProSales.getModel();
// model.setRowCount(0);
//show_Basket_in_Jtable();
JOptionPane.showMessageDialog(null,"Data "+message+" Succefully");
}else{
JOptionPane.showMessageDialog(null,"Data "+message+ " Succefully");
}
}catch (Exception ex){
ex.printStackTrace();
}}
Your query is looking for equality and also is missing some quotes, try with a LIKE clause :
String queryy = "DELETE FROM ektupotiko WHERE Αριθμος_ΔΔΥ LIKE '?%' ";
Use like :
String queryy ="DELETE FROM ektupotiko WHERE Αριθμος_ΔΔΥ like '?%' ";
executeSQLQueryy(queryy, "updated");
Related
I have db named spareparts in which all values are stored as varchar(20).
I am taking input from the user through jtextfield as a number then convert into integer.
s1(which is itemcode) and s2(which is quantity to be added to actual quantity) are the input Now I want to add this input into 'quantity'(which is also varchar) as:
public class AddStockDAO{
Connection connection;
PreparedStatement preparedStatement;
ResultSet resultSet;
Statement statement;
public AddStockDAO(String s1,String s2)
{
int num=Integer.parseInt(s2);
String sql= "select "+
" cast(quantity as INT) from spareparts"+
"set quantity+= "+num+
" cast(quantity as varchar(20))"+
"where itemcode='?'";
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "")) {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, s1);
stmt.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(AddProductGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
If I understand the problem correctly, you want to update the record in the DB according to the itemcode. So you just cast the existing value to number, add your additional value (with +) and cast it back.
int num = 0;
try {
num = Integer.parseInt(s2);
} catch (Exception e) {
System.out.println('Nope, that was not a number');
//Do something else?
}
String insertQuery = "UPDATE spareparts SET quantity = cast(cast(quantity as integer)+"+num+" as char(20)) where itemcode = "+s1+";";
try {
connection = DriverManager.getConnection(...); //add your data
preparedStatement = connection.prepareStatement(sql)
preparedStatement.executeUpdate();
} catch (Exception e) {
//Something broke
}
Also - You should use the class variables you've defined at the top of your class, so you don't have to recreate the connection later on.
But If you add more AddStockDAO, each of them will create new connection, so I'd suggest you create a database class where you setup a connection and just pass some data or a query to a method to run it on the existing connection.
I would not recommend this. How would you know if an Integer + Varchar(20) is more than 20 characters?
As #Connor has said, there is no way to make sure the result is less than 20 characters, so using a BigInteger field is much better, but if the field MUST be a varchar(20), I would recommend selecting that field from the database, doing the addition in java, and then storing the result back in the database.
Hi I have a problem with my syntax in my java code. I have a tableview which gets its data from a SQL database. I have created 3 tables in the database book, customer, order. When I click a button I want to take the selected books and add them to the order table.
Here is the code from the main program (calling the method from db):
if(table.getSelectionModel().getSelectedItems().iterator().hasNext()) {
db.insertOrder(new Bestellung(customerid,table.getSelectionModel().getSelectedItems().iterator().next()));
The table book is fixed. Just the two other tables customer,order are dynamic.
The problem:
I create the values in the order table like this
String ct = "CREATE TABLE Order (" + "Order_Id integer generated always as identity, " + "CUSTOMER_ID BIGINT" + "ISBN, CHAR(13) " + "PRIMARY KEY(Order_Id))";
and so on...
I insert into order table like this. (Here is the syntax problem in the String i That's the position where the compiler says it doesn't work..)
String i = "INSERT INTO ORDER(CUSTOMER_ID,ISBN), VALUES(?,?)";
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DriverManager.getConnection(connString);
stmt = conn.prepareStatement(i);
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
stmt.setLong(1, order.getCustomerId());
stmt.setString(2, order.getBuch().getISBN());
stmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
finally {
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
and here is the syntax error which I got
Syntax error: Encountered "ORDER" at line 1, column 13.
So how do I have to correct my syntax in the string i? Does anyone have any ideas?
INSERT INTO ORDER(CUSTOMER_ID,ISBN), VALUES(?,?)
^
The comma is superfluous. Also, in your CREATE TABLE
... + "ISBN, CHAR(13) " + ...
^
This comma is also extraneous.
If you want to use reserved words/keywords as Table name, you should:
MySQL: use ' , like : select * from 'Order'
Oracle, PostgreSQL: use " , like : select * from "Order"
But it is bad practice, try to change your table name.
You have another Error that answered by #Jim Garrison.
I have a table that contains two columns CODE where there is all the bar code and VARIABLE initialized to 0 at the beginning . I have to update the table when I scan the bar code , I have to add 1 to variable , when I scan it twice VARIABLE =2....
I have tried to do it like but it does not work .Can anyone help?
String query = "INSERT INTO TABLE (CODE,VARIABLE) VALUES(?,?) ON DUPLICATE KEY UPDATE VARIABLE='"+VARIABLE+1+"'";
try {
if (connect != null) {
PreparedStatement statement = connect.prepareStatement(query);
statement.setString(1, "%" + res + "%");
statement.setInt(2,VARIABLE );
r=statement.executeQuery();
if (r.next()) {
message = "Updated";
String code = r.getString("CODE");
int var = r.getInt("VARIABLE");
INFOSOMME.setText(message);
INFOSOMME.setText(code);
INFOSOMME.setText(var);
} else {
message = "Error";
INFOSOMME.setText(message);
}
} else {
message = "Error in connection with SQL server";
INFOSOMME.setText(message);
}
} catch (SQLException e) {
etat = false;
message = "Got an exception!";
System.err.println(e.getMessage());
}
}
});
ERROR: 08-03 09:43:44.966 30393-30393/com.example.practicas.myapplication W/System.err: Sintaxis incorrecta cerca de la palabra clave 'ON'.
I have tried to change the query to String query="INSERT INTO TABLE(CODE,VARIABLE) VALUES(?,0);" + "Update TABLE SET VARIABLE=VARIABLE+1 WHERE CODE LIKE ?"; and I got this error /System.err: The executeQuery method must return a result set.
Try to execute the following SQL command:
String query = "INSERT INTO TABLE (CODE,VARIABLE) VALUES(?,?) ON DUPLICATE KEY UPDATE VARIABLE=(VARIABLE+1)";
I have posted a comment but better here, I guess:
executeNonQuery
Updates and Inserts don't return data, so you must not use executeQuery with them (which does return information apart from the amount of rows affected)
I have a database table with the following layout:
Columns:
_________________________
id | user_name | password
But I can't delete a specified row by using the username.
I am receiving the following error:
MySQLSyntaxErrorException: Unknown column 'vipin' in 'where clause'
vipin is a value within the table.
Can anyone help me?
public void deleteFclty() {
PreparedStatement stmt = null;
ResultSet rs = null;
String username = removeText.getText();
ArrayList<String> values = new ArrayList();
String qry = "SELECT user_name From users ";
try {
stmt = (PreparedStatement) connection.prepareStatement(qry);
rs = stmt.executeQuery();
while (rs.next()) {
values.add(0, rs.getString(("user_name")));
System.out.println(values);
}
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
if (values.contains(username)) {
username = removeText.getText();
Boolean isAdmin = false;
try {
System.out.println(username);
preparedStatement = (PreparedStatement) connection.prepareStatement("DELETE FROM users WHERE user_name=" + username + "");
preparedStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
Util.showErrorMessageDialog(username + " is not found.Please try again.");
}
}
Since you're already using PreparedStatement, use it right and pass the username as parameter instead of just concatenating the Strings:
//no need to use a cast here
preparedStatement = connection.prepareStatement(
//note the usage of ? instead of concatenating Strings
"DELETE FROM users WHERE user_name=?");
//setting the first parameter in the query string to be username
preparedStatement.setString(1, username);
preparedStatement.executeUpdate();
Using this, you won't have any concatenation problems and what's better, your code won't be prone to SQL Injection.
Not directly related to your problem, but it would be better if you move the code to execute INSERT, UPDATE and DELETE statements to a single method.
public void executeUpdate(Connection con, String query, Object ... params)
throws SQLException {
PreparedStatement pstmt = con.prepareStatement(query);
if (params != null) {
int i = 1;
for(Object param : params) {
pstmt.setObject(i++, param);
}
}
pstmt.executeUpdate();
pstmt.close();
}
So your code would be dramatically reduced to:
String deleteSQL = "DELETE FROM users WHERE user_name=?";
executeUpdate(deleteSQL, username);
Note that you can create a new method based on this approach to execute SELECT statements.
Also, don't forget to close your resources. This also can be dramatically reduced using a method like this:
public void closeResource(AutoCloseable res) {
try {
if (res != null) {
res.close();
}
} catch (Exception e) {
//handle this exception...
//basic example, not meant to be used in production!
e.printStacktrace(System.out);
}
}
Note that Connection, Statement (and its children PreparedStatement and CallableStatement) and ResultSet interfaces already extend from AutoCloseable.
You haven't quoted the username you're inserting into the query, so it's being treated as a reference to a field name:
DELETE FROM users WHERE user_name='"+username+"'"
^-- ^--
Note: building queries like this leaves you open to SQL injection attacks. Used prepared statements and placeholders instead.
I think you might need some quotes round the username in the where clause
connection.prepareStatement("DELETE FROM users WHERE user_name='"+username+"'");
You are going to want to quote your Strings
"DELETE FROM users WHERE user_name="+username+"";
Like this:
"DELETE FROM users WHERE user_name='" + username + "'";
What would be better is just using PreparedStatement as it was intended:
"DELETE FROM users WHERE user_name = ?";
And then using:
preparedStatement.setString(1, username);
before calling executeUpdate
The query should look like this
preparedStatement = (PreparedStatement) connection.prepareStatement("DELETE FROM users WHERE user_name='"+username+"'");
Note : Mind the single quotes used for user_name='"+username+"'"
I am having many rows in table and I ran the same query on my database which is MySql but java ResultSet is only giving the first row of the table. Here is my code.
public ArrayList<String> getAllAlbumsName(Integer uid) {
ArrayList<String>allAlbumsName = new ArrayList<String>();
try {
String qstring = "SELECT albumname FROM picvik_picture_album WHERE " +
"uid = '" + uid + "';";
System.out.println(qstring);
connection = com.picvik.util.MySqlConnection.getInstance().getConnection();
ptmt = connection.prepareStatement(qstring);
resultSet = ptmt.executeQuery();
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
resultSet.close();
ptmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return allAlbumsName;
}
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
If you would like to get all rows, it should be:
while(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
The while statement continually executes a block of statements while a particular condition is true
Note: As #BalusC commented, your code would introduce SQL Injection attack, it is better to use ptmt.set... Instead of constructing SQL String manually.
try while(resultSet.next()) {
instead of if (resultSet.next()) {
Change if (resultSet.next()) { to while (resultSet.next()) {