SQL Syntax Problems - mysql

Im trying to do this:
String insertQuery=" DELETE FROM Accounts WHERE Username= " + Username + ";";
But im getting this error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'sam' in 'where clause'
Its getting the right username etc I know this by testing, I assume the syntax is wrong but im getting no syntax errors?
The table is called Accounts. The coloums are Username & Password,

You are missing single quotes. In your case(it's string) variable need to be wrapped in them or it'll be interpreted as column.
String insertQuery = "DELETE FROM Accounts WHERE Username = '" + Username + "'";
Recommendation:
Hence i recommend you to use placeholders to avoid this kind of problem. Don't forget to care about a security(SQL Injection for instance). It's worth to say that parametrized statements are also more human-readable, safer and faster as well.
I don't like "hardcoded" queries. Let's imagine a scenario if you had a table with ten columns and imagine how you query will look in this case: absolutely human-unreadable.
An usage of parametrized statements is always very efficient and comfortable practise. Your code looks good and becomes human-readable and what is "main" solution is much more safer and cleaner.
Have look at PreparedStatements. Basic example:
private final String deleteQuery = "DELETE FROM Accounts WHERE Username = ?";
public boolean deleteObject(String username) {
Connection c = null;
PreparedStatement ps = null;
try {
c = DataSource.getConnection();
ps = c.prepareStatement(deleteQuery);
ps.setString(1, username); // numbering starts with 1 not 0!
return ps.executeUpdate() > 0;
}
catch (SQLException ex) {
System.out.println("Error in deleteObject() method: " + ex.getMessage());
return false;
}
finally {
if (c != null) {
try {
c.close();
}
catch (SQLException ex) {
System.out.println("Error in closing conn: " + ex.getMessage());
}
}
}
}

If username is a varchar you need to add single quotes around the value in the where clause.
String insertQuery=" DELETE FROM Accounts WHERE Username= '" + Username + "';";
Since the value is not quoted its identifying the username, I'm assuming its Sam as a column.

Related

Java FXML - NetBeans - Delete from Table - MySQL

I get the following error when I attempt to delete a row from TableView:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[value: 3]' at line 1
What I want: Once a row from TableView is selected, I want to delete it from database.
#FXML
void delete(ActionEvent event) {
try {
int pos;
pos = (int) tabelCustomers.getSelectionModel().getSelectedIndex();
Customers c;
c = tabelCustomers.getItems().get(pos);
SimpleIntegerProperty idc = c.idc;
String query;
query = "DELETE FROM customers WHERE customers.idc = " + idc;
try (Statement stm = cnx.createStatement()) {
stm.executeUpdate(query);
}
} catch (SQLException ex) {
Logger.getLogger(CustomersTableController.class.getName()).log(Level.SEVERE,
null, ex);
}
}
What am I missing? I have tried a lot of possible solutions, nothing works.
Basically, when a user clicks on the row in a table and then clicks on the "remove" button, that row should be deleted from table and DB.
Thanks in advance.
SimpleIntegerProperty idc = c.idc;
String query = "DELETE FROM customers WHERE customers.idc = " + idc;
When an Object (that is not a String) is used in string concatenation it is automatically converted into a String by calling toString() on it. The string representation of SimpleIntegerProperty is not simply its value, which means your query ends up looking something like:
DELETE FROM customers WHERE customers.idc = IntegerProperty [bean: <some_instance>, name: idc, value: 42]
Which is obviously not valid SQL. You need to extract the value of the property and use that as part of the query. However, you should not use string concatenation when creating SQL queries in the first place. You should instead be using a PreparedStatement with parameters. For example:
String query = "DELETE FROM customers WHERE customers.idc = ?";
try (PreparedStatement ps = cnx.prepareStatement(query)) {
ps.setInt(1, idc.get());
ps.executeUpdate();
}

Can't delete form database SQLGrammarException

I want to DELETE column from base in hibernate where my inserted -regBroj- parameter is same as one in a base.
This is my method in controller for deleting.But i constantly get
SQLGrammarException:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'BG026CH' in 'where clause'
This 'BG026CH' is value of regBroj that i use as a parameter to find vehicle in database and delete it.And i insert it in text area in adminPage.
public String izbrisi(String regBroj) {
List<Vozilo> lista = listaj();
Session s = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction t = s.beginTransaction();
for (int i = 0; i < lista.size(); i++) {
if (regBroj .equals(lista.get(i).getRegBroj())) {
String izbrisiquery = "DELETE FROM Korisnik WHERE brojLk=" + regBroj + "";
Query q = s.createQuery(izbrisiquery);
int a = q.executeUpdate();
t.commit();
return "adminPage";
}
}
t.commit();
return "error";
}
Please replace below string with these one
String izbrisiquery = "DELETE FROM Korisnik WHERE brojLk='" + regBroj + "'";
You should consider using prepared statements because they will automatically take care of escaping field values with quotes, and they will also protect you from SQL injection.
// obtain a Connection object using your Hibernate session, or through some other means
Connection conn = getDBConnection();
for (int i = 0; i < lista.size(); i++) {
if (regBroj .equals(lista.get(i).getRegBroj())) {
String izbrisiquery = "DELETE FROM Korisnik WHERE brojLk = ?";
PreparedStatement ps = conn.prepareStatement(izbrisiquery);
ps.setString(1, regBroj);
ps.executeUpdate();
t.commit();
return "adminPage";
}
}
To see how SQL injection works, or how a malicious user could wreck the Korisnik table, imagine that someone hacks the UI to pass a value of '' OR TRUE for brojLK. This is what the resulting DELETE statement would look like:
DELETE FROM Korisnik WHERE brojLk = '' OR TRUE
In other words, this injected query would drop your entire table! Prepared statements would choke on this input and a hacker would not get as far as executing the query.

Embedded SQL INSERT Using Dialog Boxes

I'm currently trying to insert new data into an existing table in my database using embedded SQL. I need to be able to enter my data in a dialog box and then have it shown back to me in a dialog box after it has executed.
My problem seems to be with the "s.executeUpdate(input);" for it tells me that I have an error in MySQL syntax. I'm not really sure how to fix it, or how to change the syntax. Help would be much appreciated!
Connection c = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://localhost:3306/company - final project", "root", "");
String query = "INSERT INTO works_on (ESSN, PNO, HOURS)" + "Values (?, ?, ?)";
Statement s = c.prepareStatement(query);
String input = JOptionPane.showInputDialog(null, "Info to be Inserted: ");
s.executeUpdate(input);
JOptionPane.showMessageDialog(null, "Data Inserted: " + input);
c.close();
}
catch (Exception e)
{
e.printStackTrace();
}
You're prepared statement requires 3 parameters, but you did not add any. need to call s.addXXX in the proper order to specify the 3 values to insert, wheres "XXX" is the appropriate type for the values

Dynamically adding columns for SQL PreparedStatement - still safe against injection?

I am trying to prevent SQL injection in my Java program. I want to use PreparedStatements to do this, but I don't know the number of columns or their names in advance (the program allows administrators to add and remove columns from the tables). I'm new to this, so this may be a silly question, but I'm wondering if this approach is safe:
public static int executeInsert( String table, Vector<String> values)
{
Connection con;
try {
con = connect();
// Construct INSERT statement
int numCols = values.size();
String selectStatement = "INSERT INTO " + table + " VALUES (?";
for (int i=1; i<numCols; i++) {
selectStatement += ", ?";
}
selectStatement += ")";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
// Set the parameters for the statement
for (int j=0; j<numCols; j++) {
prepStmt.setString(j, values.get(j));
}
System.out.println( "SQL: " + prepStmt) ;
int result = prepStmt.executeUpdate();
con.close() ;
return( result) ;
} catch (SQLException e) {
System.err.println( "SQL EXCEPTION" ) ;
System.err.println( "Inserting values " + values + " into " + table);
e.printStackTrace();
}
return -1;
}
Basically I'm creating the String for the statement dynamically based on how many values are passed in (and therefore how many columns are in the table). I feel like it's safe because the PreparedStatement is not actually created until after this string is made. I may make similar functions that take in actual column names and incorporate them into the SQL statement, but these will be produced by my program and not based on user input.
Any time you have values like table being inserted into your query without escaping, you should test against a whitelist of known-good values. This prevents people from being creative and causing trouble. A simple dictionary or array of valid entries usually suffices.
Using a prepared statement is a good idea, but be sure the statement you're preparing doesn't allow for injections right from the start.

How to insert data taken from user into mysql using jdbc

I'd like to get a data (e.g. name) from user and insert it into mysql using JDBC.
I'm trying to do something like this:
String uName = Username.getText(); (where uName is the name of the texfield)
Then I'd like to insert this 'uName' variable into mysql. I knew it wouldnt work, but I gave it a shot, and tried to do it with the following query:
statement.executeUpdate("INSERT INTO users(username) VALUES(uName)");
(Where username is the name of the column.)
It didnt work :) Any suggestions?
Assuming you are opening connection to your database in the right way, you can do something like:
String connString = "jdbc:mysql://localhost:3306/<db_name>?user=<user>&password=<password>";
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(connString);
// open connection
// ...
try
{
String query = "INSERT INTO users (username) VALUES (" + uName + ")"
statement = connect.createStatement();
statement.executeUpdate(query);
}
catch (SQLException se)
{
es.printStackTrace();
}