Java FXML - NetBeans - Delete from Table - MySQL - 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();
}

Related

How can I detect an access DB table with no columns?

I have a support tool I have written that allows me to create a table in MS Access DB file. Because of the support, I set it so it just creates the table without any columns defined. There is another part of the same program which allows column creations. However when I select the table in my list, I try to load the table. Since the table is empty, the system throws an error at the Fill (I understand the Select is the cause). Is there a way to ask if a table has any columns before trying to load that table?
public static bool ConnectToDatabase(string dbTable)
{
return ConnectToDatabaseWStr(dbTable, "Select * From `" + dbTable + "`");
}
public static bool ConnectToDatabaseWStr(string dbTable, string strSQL)
{
try
{
conn = new OleDbConnection(connectionString);
}
catch (Exception e)
{
LogFile.write(1, "DataAccess: error detected when creating OLEDBConnection.\nConnection string:\n" + connectionString + "\n" + e.ToString() + "\n");
}
try
{
dataAdapter = new OleDbDataAdapter(strSQL, conn);
dataAdapter.Fill(DataSetList[iCurrDataSetListIndex].DataSetInstance, dbTable);
This is easy if there are columns.
You can even go SELECT * from tableName where ID = 0
And then for each the column names. However, while the above will return 0 rows, the columns still do come through. However, without ANY columns, then the above will fail, and you would in theory have to know the "ID" column existed.
You can thus get oleDB provider to return a table as a "schema". This is table of ROWS of the defined table. Thus you can use this:
If NO rows are returned, then we don't have a table that lays out and defines the schema:
var strTableName = "tblHotels";
OleDbConnection myCon = new OleDbConnection(My.Settings.TestDB);
myCon.Open();
string[] SchemaParams = new[] { null, null, strTableName, null };
DataTable MyTable = myCon.GetSchema("Columns", SchemaParams);
if (MyTable.Rows.Count == 0)
// no columns for table
Debug.Print("no columns in table");
else
foreach (DataRow MyRow in MyTable.Rows)
Debug.Print(MyRow("Column_Name") + "->" + MyRow("Data_Type"));

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.

Checking database's username and data if they match the user info or not

I want to check that the username and data which is already in database is match with the user info or not. I have written some code but it doesn't select a row.
Here is my code:
public boolean iscorrect(String name , String pass){
boolean check=false;
openConnection();
Statement st =null;
ResultSet rs = null;
try{
st = conn.createStatement();
String q = "Select * from signup where email = '"+name+"'" ;
rs=st.executeQuery(q);
System.out.println(rs.getString(1)+" "+rs.getString(2));
if(rs.getString(1).equals(name) && rs.getString(2).equals(pass)){
check = true;
}
}catch(SQLException e){
e.printStackTrace();
}
return check;
}
You need to first call rs.next() to put the cursor at the first row of data. This will return false if there is no data.
In addition to that:
please use PreparedStatement and bind variables to avoid SQL injection
you could put the checks into the WHERE clause instead of loading the whole row
please don't store clear text passwords, use a cryptographic hash function

SQL Syntax Problems

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.

How can I display data into my Jtextarea from my data base Mysql

I have problem when I try to display data(the result of a query) from my database mysql to my jTextarea, when I compile I have an error exception like:
SQL Exception: java.sql.SQLException: Can not issue SELECT via executeUpdate()
I have used a "select" query from my table where the name is the name written in my jTextFieldNom,this is my code, I hope that some one help me because I don't know how to resolve the problem, I 'm sure that my query is correct but I don't know where is the problem.
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
instruction = connexion.createStatement();
int rowsEffected = instruction.executeUpdate(SQL);
jTextArea1.append(rs.getString("description"));
}
...... //bloc catch
This line is executing a Select statement which is throwing the error.
int rowsEffected = instruction.executeUpdate(SQL);
You don't need this line because you aren't updating your database.
Also change the append to setText
jTextArea1.setText(rs.getString("description"));
Try this:
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
jTextArea1.setText(rs.getString("description"));
}