How should I delete a row using a java variable in SQL table?
I am trying to delete a record from table member (with two columns, name and year) using what the user has input (variable newName and newYear). I want to find the row that has the same record as what the user has input (name = newName && year=newYear) and delete it. However, this code doesn't change anything on the table (no row is deleted although what I have input is correct). What's wrong with my code?
String newName = memName.getText();
int newYear = parseInt(memYear.getText());
are the variables used in the code below.
try {
s = c.createStatement();
t = "DELETE FROM member " +
"WHERE (name='" + newName + "'&& year='" + newYear + "')";
s.executeUpdate(t);
s.close();
c.commit();
c.close();
} catch (SQLException ex) {
Logger.getLogger(AddMember.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(null, "Saved.");
memName.setText(null);
memYear.setText(null);
I want the row with the info the user input to be deleted from the table, but it didn't make any changes to my table.
the problem you have is that in SQL you cannot use && instead use AND as shown in the following code:
t = "DELETE FROM member " +
"WHERE (name='" + newName + "' AND year='" + newYear + "')";
Related
I'm trying to make CRUD (Create, Read, Update, Delete) to my projects. But it seems the "update" doesn't work. It keeps saying
java.sql.SQLSyntaxErrorException : You have an error in your SQL syntax; check the manual that coresponds to your MariaDB server version for the right syntax to use near "Number" = 0813874810 WHERE Name = "Gregory" at line 1)
What the solution for this?
Here is my code:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata", "root", "");
String sql = "UPDATE employeetab SET Name = '" + txtEmployeeName.getText()
+ "',Address = '" + txtEmployeeAddress.getText()
+ "',Gender = '" + gender_type
+ "',Phone Number = '" + txtEmployeePhone.getText()
+ "' WHERE Name = '" + txtEmployeeName.getText() + "'";
stm = conn.prepareStatement(sql);
stm.execute(sql);
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
Problem comes from the space in column Phone Number. To make it work you need to escape the column name with `.
UPDATE employeetab
SET Name = 'something',Address = 'some address',Gender = 'whatever',`Phone Number` = '000000000'
WHERE Name = 'something';
You should follow sql naming conventions, normally words in column names are separated by _. Your column name should be - phone_number.
Also, as mentioned in comments, you should not just add user input into sql queries, because you are leaving yourself wide open for sql injection.
You need to follow the naming conventions , their is space between 'Phone Number' column you should not write like this you need to add _ in between of this two.
try this :
String gender_type = null;
if (ButtonM.isSelected()){
gender_type = "Male";
}else if(ButtonFM.isSelected()){
gender_type = "Female";
}
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata","root","");
String sql = "UPDATE employeetab SET Name = ? ," +
" Address = ? ," +
" Gender = ? ," +
" Phone Number = ? ," +
" WHERE Name = ? ," ;
PreparedStatement pStmt = conn.prepareCall(sql);
pStmt.setString(1, txtEmployeeName.getText()+"");
pStmt.setString(2, txtEmployeeAddress.getText()+"");
pStmt.setString(3, gender_type+"");
pStmt.setString(4, txtEmployeePhone.getText()+"");
pStmt.setString(5, txtEmployeeName.getText());
pStmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
its cleaner and should work.
ResultSet rs = stat.executeQuery("select * from donor where username = '" + username + "'");
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
System.out.println(Updatesentence);
stat.executeUpdate(Updatesentence);
Guys I am trying to make an update to an SQL database with this code and although I am not getting an error somewhere the code does not work with the desired result. The
System.out.println(Updatesentence);
is not printed and the update is not performed. I know there probably is somewhat of a syntax error on my String declaration, but I cannot work it out.
You have this:
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
So if the user's blood type is AB...
update bank set AB = AB + 1 where name = 'JohnSmith'
And that obviously won't work. You need to indicate the column in the database you want to be updating.
One of the most important things you need to remember when writing SQL statements, is to separate the query literal from the query arguments. This allows protection from SQL Injection and also makes it possible for the DB to reuse the query with different arguments (and "hard parsing" / optimizing the query only once). The way you do this with JDBC, is through prepared statements:
try (PreparedStatement queryPS = myConnection.prepareStatement(
"select * from donor where username = ?");
PreparedStatement updatePS = myConnection.prepareStatement(
"update bank set bloodtype = ? where name = ?");) {
queryPS.setString(1, username);
ResultSet rs = queryPS.executeQuery();
if (rs.next()) {
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
updatePS.setString(1, type);
updatePS.setString(2, username);
updatePS.executeUpdate();
}
} catch (SQLException e) {
// handle it
}
When you use prepared statements, you don't need to worry about concatenating the inputs into the query; they will be sanitized and injected automatically. If you're doing things the "wrong way", it's really easy to make a mistake when you construct the query piece by piece from different variables in your code, and this is exactly what happened with the misplaced type variable in your example.
Your update statement is wrong. It should be :
String Updatesentence = "update bank set bloodtype = " + type + " + 1 where name = '" + name + "'" ;
I am connecting to a SQLite database through java using JDBC.
Schema:
WorkInfo(id, job, salary)
Person(id, name)
This query below runs fine in my database, but when I try it with JDBC:
ResultSet rs = statement.executeQuery("select * from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("Person.id")); //column does not exist
System.out.println("name: " + rs.getString("name")); //works fine
Output:
If using person.id: no such column: 'person.id'
Without specifying: ambiguous column name 'id'
I've tried using both WorkInfo and Person and using aliases but it keeps throwing the same ambigious column name (if left as id) or column does not exist.
It's always a good practice to explicitly retrieve the columns you want. I would change the query to be:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id, person.name from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt(4));
System.out.println("name: " + rs.getString(5));
In this case, you can use the column index instead of the label.
Or using the AS clause:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id as personId, person.name as personName "
+ "from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt("personId"));
System.out.println("name: " + rs.getString("personName"));
After a day of working on this, I achieved it by using resultSet.getMetaData().
private int getIndexFromMeta(String column) {
try {
ResultSetMetaData meta = resultSet.getMetaData();
String[] subs = column.split("\\.", -1);
String tableName = subs[0];
String columnName = subs[1];
for (int i = 1; i <= meta.getColumnCount(); i++) {
if (meta.getTableName(i).equals(tableName) && meta.getColumnName(i).equals(columnName)) {
return i;
}
}
} catch (SQLException e) {
Log.trace(e);
}
return 0;
}
It seems like the ResultSet you're getting back holds the following columns:
id
name
id
job
salary
You have two columns named "id" (none named "Person.id"), so when you try to get its' value you either
Ask for "id" which is ambiguous (which id?)
Ask for "Person.id" which does not exist
Simply try specifying in your query the columns you want and giving them unique aliases. For example:
ResultSet rs = statement.executeQuery("select Person.id AS 'personid', name from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("personid"));
System.out.println("name: " + rs.getString("name"));
I am trying to develop a program where you want to add a new book ( title, author, date,...)
but i do not want to add the author multiple times..
i want the program to check if the author already exists in the table, if not it will add him... here is my code :
public void insert_bk(String m, String a, String b, String c, String d, String e) {
String sql="Select * from author where Full_Name='"+b+"'";
System.out.println(sql);
try {
opencn();
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while (rs.next()) {
String id=rs.getString("Author_ID");
System.out.println(id);
st.executeUpdate("INSERT into book (`Book_ID`,`Title`,`Author_ID`,`Date_of_release`,`Theme`,`Edition`)"+ "VALUES ('" + m+ "','" + a+ "','" + id+ "', '" + d+ "', '" + e+ "', '" + c+ "')");
}
}
catch(SQLException exp) {
System.out.println(exp.getMessage());
}
}
In this code it just checks if the Author exists and adds the book... how can i make the condition that if the author does not exist it will add him along with the book?
Any ideas?
Thank you in advance :)
Instead of using a while-loop you should put rs.next() into an if-statement. If the call returns false no author is present and it has to be inserted.
you can do this stored procedure
declare #i int
Select #i=count(*) from author where Full_Name=#FullName
IF(#i < 1)
BEGIN
// INSERT
END
This might help
String query = "Select * from author where Full_Name='"+b+"'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader rdr;
con.Open();
cmd.ExecuteNonQuery();
rdr = cmd.ExecuteReader();
if (rdr.Read()) { // if you have an author
//do your updation code here
}
else {
//if rdr.Read() gives 0 which will be the case when our
//author wont exist past the code for adding an author here
}
You can make a conditional insert by adding the keyword IGNORE into the statement. Depending on which SQL database you are using the answer is slightly different. I'll demonstrate here the two ways for MySQL and sqlite, but of course there are more.
For MySQL
INSERT IGNORE INTO authors VALUES(?,?...,?)
For SQLite
INSERT OR IGNORE INTO authors VALUES(?,?,...,?);
I have some problems with JDBC's rs.getString("column_name") basically it would not assign the value recieved from the query result, I have a String ris which is supposed to get the row name from rs.getString, for semplicity of the question I'm using ris and my query returns only one row. This is the code:
//It returns null, or any other values I use to initialize the variable
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
}
else {
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
I semplified the code, so it would be easy to focus on where the problem is.
Thanks in advance!
if (rs.last())
while (rs.next())
That won't work, because after you have called last , you are at the last row and next will always return false (it would return true and take you to the next row if there was one left).
And please use a prepared statement with bind variables!
And finally close ResultSet and Connection (or use Jakarta Commons DbUtils).
try this, just remove the rs.last() call in the if condition.. also i agree with #Thilo about using prepared statements.
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
rs.first(); // go to first record.
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();