Hello I am trying to delete a row from my database. I am getting no errors but it is doing nothing, any help or advice would be great!
public static void DeleteRow(String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = " + name + ";");
st.executeUpdate();
} catch(Exception e) {
System.out.println(e);
}
}
I guess name is a varchar type in DB so do like this
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = '" + name + "';");
enclose name within single quotes '
Also this is not the way you are using is not the proper way of using Preparedstatement
Us the following way:
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate();
// your full code after Proper PreparedStatement
public static void DeleteRow(String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate();
} catch(Exception e) {
System.out.println(e);
}
}
You should never create a SQL statement in Java with String concatenation, it will be vulnerable to sql injection. Please do it this way.
String selectSQL = "DELETE FROM Table WHERE name = ?";
connection.prepareStatement(selectSQL);
preparedStatement.setString(1, name);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "MANASH_APPN","MANASH");
PreparedStatement ps = con.prepareStatement("delete from EMP21 where empid = ?");
ps.setInt(1,90);
ps.executeUpdate();
con.commit();
System.out.println("Records Delete Successfully....");
con.close();
try this bro. use Statement
Statement stmt = connection.createStatement();
String SQL = "DELETE FROM Table WHERE name = '"+name+"'";
stmt.executeUpdate(SQL);
Every open connection must be closed, or it won't get implemented and no errors will be displayed. First learned lesson.
public static void DeleteRow(String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = " + name + ";");
st.executeUpdate();
connection.close();
} catch(Exception e) {
System.out.println(e);
}
}
Hope this helps
this will work
String del="DELETE FROM table WHERE name =('" + name + "')";
:)
Related
The problem is that I am trying to set a wild card in a PreparedStatement but the setString statement is giving me the error above.
I have tried changing it to a setObeject statement with multiple different types like Types.VARCHAR. I have tried declaring the PreparedStatement in different places, and I have tried declaring 'name' in the method and in the class.
public String getTemplateText(String name) {
try (
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT templateText FROM TEMPLATE WHERE " +
"templateTag = ?");
stmt.setString(1 , name); // this is the line that has the problem!
ResultSet rs = stmt.executeQuery()
) {
System.out.println("Set Text...");
String tempText = rs.getString("templateText");
return tempText;
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
/* this is the SQL code for the table that I am trying to query */
CREATE TABLE TEMPLATE
(
templateID INTEGER PRIMARY KEY IDENTITY(1,1)
, templateText TEXT
, templateTag CHAR(25)
);
You can't set the stmt parameter in your try-with-resources (because binding the parameter is void and not closable). Instead, you can nest a second try-with-resources after you bind the parameter. Like,
public String getTemplateText(String name) {
try (Connection conn = getConnection();
PreparedStatement stmt = conn
.prepareStatement("SELECT templateText FROM TEMPLATE WHERE " +
"templateTag = ?")) {
stmt.setString(1, name);
try (ResultSet rs = stmt.executeQuery()) {
System.out.println("Set Text...");
String tempText = rs.getString("templateText");
return tempText;
}
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
I am trying to list MySQL databases and their tables with Java. For now, I have two databases as "Database_Services with MySQL_Database_Service, MSSQL_Database_Service, and Directory_Services with Active_Directory, OpenLDAP tables. I get the output for Database_Services and its tables but I do not get the other ones.
public class connectMySQL implements serverConnection{
Connection conn;
Statement stmt;
public void connect(String dbName){
String url;
try {
if(dbName.equals("")){
url = "jdbc:mysql://x:x/";
}
else{
url = "jdbc:mysql://x:x”+ dbName;
}
String username = “x”;
String password = "x";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
}
catch (SQLException ex)
{
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}
public class listInf extends connectMySQL implements listInfrastructure {
public void list() {
String dbName;
ResultSet rs;
try{
connect("");
String str = "SHOW DATABASES";
ResultSet resultSet = stmt.executeQuery(str);
while(resultSet.next()){
dbName = resultSet.getString("Database");
if(!dbName.contains("schema") && !dbName.equals("mysql")){
System.out.println(dbName);
rs = stmt.executeQuery("SHOW TABLES IN " + dbName);
while (rs.next()) {
System.out.println("\t" + rs.getString("Tables_in_" + dbName));
}
}
}
}
catch(SQLException e){
System.out.println("Error");
}
}
}
I want to get an output like:
Database_Services:
MySQL_Database_Service.
MSSQL_Database_Service.
Directory_Services:
Active_Directory_Service.
OpenLDAP_Service.
You are using the same Statement for multiple queries. You cannot do that. From the Javadoc of Statement:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
Connection conn1 = DriverManager.getConnection(url, username, password);
Connection conn2 = DriverManager.getConnection(url, username, password);
Statement statement1 = conn1.createStatement();
Statement statement2 = conn2.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SHOW TABLES IN DB1");
ResultSet resultSet2 = statement2.executeQuery("SHOW TABLES IN DB2");
while (resultSet1.next()) {
System.out.println("");
}
while (resultSet2.next()) {
System.out.println("");
}
if you have more than 2 database, then simply you can use loop for to get the results.
You can use the meta information database information_schema.
SELECT
TABLE_SCHEMA,
TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA IN ('Database_Services', 'Directory_Services')
ORDER BY TABLE_SCHEMA
I tried to save / edit / delete a new row in the database. writing in the gui values to be saved with getText ()
here is the code
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql;
sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (txt_isbn, txt_disp, txt_titolo, txt_casa, txt_autore, txt_genere, txt_prezzo)";
stmt = conn.createStatement();
emps = stmt.executeQuery(sql);
String ISBN= txt_isbn.getText();
String DISPONIBILITA= txt_disp.getText();
String TITOLO= txt_titolo.getText();
String CASA_EDITRICE= txt_casa.getText();
String CODICE_AUTORE= txt_autore.getText();
String GENERE= txt_genere.getText();
String PREZZO = txt_prezzo.getText();
JOptionPane.showMessageDialog(null, "SALVATO");
}catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null, e);
}
finally
{
try{
if (emps != null)
emps.close();
}
catch (SQLException e) { }
try
{
if (stmt != null)
stmt.close();
}
catch (SQLException e) { }
}
Getting this error: column not allowed here
Above code just takes care of insert operation. How can I delete and modify table record?
You have asked 2 different questions here
1. Column not allowed here
This happened because you have not passed values for any of parameter into insert statement.
I am not sure about your requirement however I will use PreparedStatement for this scenario.
Example
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "MindPeace");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement .executeUpdate();
2. This code is only to save the data, delete, and modify an entire row how can I do?
Answer is very simple. You have to write code for the same :)
You need 3 SQL statement which has DELETE and UPDATE operation just like insert in above example.
String sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, "
+ "CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.createStatement()) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);
String ISBN = txt_isbn.getText();
String DISPONIBILITA = txt_disp.getText();
String TITOLO = txt_titolo.getText();
String CASA_EDITRICE = txt_casa.getText();
String CODICE_AUTORE = txt_autore.getText();
String GENERE = txt_genere.getText();
BigDecimal PREZZO = new BigDecimal(
numberFormat.parse(txt_prezzo.getText()).doubleValue())
.setScale(2);
stmt.setString(1, ISBN);
stmt.setString(2, DISPONIBILITA);
stmt.setString(3, TITOLO);
stmt.setString(4, CASA_EDITRICE);
stmt.setString(5, CODICE_AUTORE);
stmt.setString(6, GENERE);
stmt.setBigDecimal(7, PREZZO);
int updateCount = stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "SALVATO");
} catch(SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
Try-with-resources closes the stmt automatically.
The prepared statement replaces the value in the SQL with something like:
INSERT INTO table(column1, colum2, ....)
VALUES('De\'l Rey',
1234.50,
...)
for:
"De'l Rey"
1.234,50
updateCount should be 1 on success.
Wooow..true!!
I created three buttons to delete / update / insert and now it all works and automatically updates the tables.
you've been very very great. Thank you very much.
one last thing.
if I wanted to insert an error message when I delete / update etc "book not found" I tried to create an if:
Boolean found = false;
try{
sql= delete......
etc
if (!found)
JOptionPane.showMessageDialog(null, "NOT FOUND","ERRORE",JOptionPane.WARNING_MESSAGE);
etc...
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql= "DELETE FROM progetto.libro WHERE isbn =?"; /
pst=(OraclePreparedStatement) conn.prepareStatement(sql);
pst.setString (1, txt_isbn.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "ELIMINATO");
Update_table();
txt_isbn.setText("");
txt_disp.setText("");
txt_titolo.setText("");
txt_casa.setText("");
txt_autore.setText("");
txt_genere.setText("");
txt_prezzo.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
if you find the book must exit the book removed, or "not found". but as I deployed I always come out "deleted". why?
thanks again
I am developing an application with java on netbeans/windows 7. I was trying to insert data to database with PreparedStatement using SQL. So this is my code;
private void addInfoActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn;
PreparedStatement pst;
String url = "jdbc:derby://localhost:1527/records";
String SQL_INSERT = "INSERT INTO records"+
"VALUES(?,?,?)";
String name, surname, number;
try {
conn = DriverManager.getConnection(url, "system", "app");
System.out.println("connected to db");
pst = conn.prepareStatement(SQL_INSERT);
name = nameField.getText();
surname = surnameField.getText();
number = numberField.getText();
System.out.println("got data from textfields");
pst.setString(1, name);
pst.setString(2, surname);
pst.setString(3, number);
System.out.println("variables set");
pst.executeUpdate();
System.out.println("sql command executed");
pst.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(addition.class.getName()).log(Level.SEVERE, null, ex);
}
}
But I got an error like this;
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "?" at
line 1, column 27.
Name of my table is records and it has three coloumns named; name, surname and number. As I can understand from the println lines, there is a problem with that line;
pst = conn.prepareStatement(SQL_INSERT);
or maybe I created SQL_INSERT string and SQL code wrong. I couldn't figure out what is the problem exactly.
You're missing a space in
String SQL_INSERT = "INSERT INTO records"+
"VALUES(?,?,?)";
When you do the concatenation, it produces "INSERT INTO recordsVALUES(?,?,?)"
Change it to
String SQL_INSERT = "INSERT INTO records"+
" VALUES(?,?,?)";
I successfully can delete an integer but when I tried to make it a STRING it says
"unknown column itemtodelete in where clause but my ITEMTODELETE is a STRING declared in the database not an integer how much It doesn't delete a STRING?
below is my code:
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
int del = (prompt):
if (del == JOptionPane.YES_OPTION){
DelCurRec();
}
}
public void DelCurRec() {
String id = field.getText();
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
try {
Class.forName(connectio);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);
}
Statement stmt = null;
Connection con = null;
//Creates connection to database
try {
con = DriverManager.getConnection("Connection");
stmt = con.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);
}
//Execute the SQL statment for deleting records
try {
stmt.executeUpdate(SQL);
//This closes the connection to the database
con.close();
//This closes the dialog
JOptionPane.showMessageDialog(null,"Deleted Succesfully","Delete Successful",JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);
}
}
Do NOT use a Statement use a PreparedStatement instead, otherwise your application will be vulnerable to SQL injections. E.g. someone enters a string like: "'; drop table inventory; --"
The corresponding prepared statment would look something like:
String SQL = "DELETE FROM inventory WHERE ItemCode = ? ";
PreparedStatement pstmt = null;
// get a connection and then in your try catch for executing your delete...
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeUpdate();
try changing the line:
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
to
String SQL = "DELETE FROM inventory WHERE ItemCode = '"+id+"' ";
I think you need to pass Integer.parseInt(id) and not id...assuming your id is int
This worked for me:
Statement stmt=con.createStatement();
stmt.executeUpdate("DELETE FROM student WHERE reg_number='R18854';");