Embedded SQL INSERT Using Dialog Boxes - mysql

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

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();
}

p:autocomplete tag using database

I want to use autocomplete in inputTextArea. I am doing it using values from the database. I have words, digits, symbols(like #) stored in the database.
The problem is when I try typing in the textArea, the whole list of things appears. Instead, I just want only those options to come which matches the input written in the textArea, kind of autocomplete feature but it fetches values from a database.
Given below is the java code that I have written so far.
public class DbConnect {
public List<String> completeArea(String query1) {
ResultSet rs;
Statement st;
Connection con;
PreparedStatement pst;
List<String> result = new ArrayList<String>();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/company", "root", "");
try {
query1 = "select name from labels";
pst = con.prepareStatement(query1);
rs = pst.executeQuery();
while (rs.next()) {
result.add(rs.getString("name"));
}
} catch (Exception ex) {
System.out.println(ex);
}
} catch (Exception ex) {
System.out.println("error occured" + ex);
}
System.out.println("size is " + result.size());
return result;
}
I do not want to specify any particular letter for searching in the database, it should pick automatically when the user types in. Any help would do good. Thanks a lot.
In your example the query1 parameter of the completeArea method is the user input but you overwriting it with your query. Try with
public List<String> completeArea(String input) {
...
String query = "select name from labels where name like ?";
pst = con.prepareStatement(query);
pst.setString(1, input + "%");
...
}
Edited according to #Slaw comment. Thanks for the correction. :)
I would use <p:autoComplete /> instead of inputTextArea for this usecase.
You can find a good tutorial in the official PrimeFaces site.
Your query is
select name from labels
that will give all labels's name...
I do not want to specify any particular letter for searching in the database, it should pick automatically when the user types in. Any help would do good.
If you want some matching you must specify a condition

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.

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();
}