Insert SQL in Java syntax - java

try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/pizzabaseaccount", "root", "");
Statement st = con.createStatement();
String sql ="insert into pizzaorder (PizzaType,PizzaChosen,ToppingsDetails,CrustType,PizzaSize,PizzaQuantities,PizzaTotalPrice)"
+"values ('"+pizzatype+"','"+pizzachosen+"','"+toppingsdetails+"','"+crusttype+"','"+pizzasize+"','"+pizzaquantities+"','"+totalprice+"')";
st.executeQuery(sql);
JOptionPane.showMessageDialog(null, "Order Complete");
}catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error");
}
I get "Error". It wont insert the data on the pizzabaseaccount database. pizzaorder is the table name btw. I don't know whats wrong with the code. Im a beginner on Java. Btw, the pizzatype , pizzachosen, toppingdetails, crusttype, pizzasize, pizzaquantities, and totalprice are String variables.

Check that pizzatype pizzachosen and all the others do not contains the "'" carachter; if so, you should escape it.
Anyway, this is not a good way to create an SQL query.
Use bind parameters --> read the API reference

Related

adding Database Values using Java gui

So I'm just really new with the whole database getting connected to Java and for my project i decided to integrate some gui since it's seems to make things easier and user friendly. For some reason, I can't add values because I'm getting asked where the VALUES keyword is even though it's there. Can someone help? really lost here :(
try{
//get connection
DBconnection dbconn = new DBconnection();
dbconn.login("homeuser", "12345");
dbconn.connect();
con =dbconn.getConnection();
//insert values
Statement statement = con.createStatement();
String sql =("INSERT INTO StudentInfo"+
"VALUES('first_name,'last_name,'StudID)");
statement.executeUpdate(sql);
JOptionPane.showConfirmDialog(rootPane, "Record Added.");
con.commit();
first.setText("");
last.setText("");
idText.setText("");
}catch(SQLException sqlex){
System.out.println(sqlex.getErrorCode()+" "+sqlex.getMessage());
}
You are missing a space. added after StudentInfo. check now.
//insert values
Statement statement = con.createStatement();
String sql =("INSERT INTO StudentInfo "+
"VALUES('first_name’,'last_name’,'StudID’)");
statement.executeUpdate(sql);

difficult time inserting data with textfield( jdbc swing)

My insert into is giving me issues.
Im pretty sure the Jtextfield is the problem.
If anyone can give me a nudge in the right direction I would greatly appreciate it.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#//localhost:1521/xe";
Connection conn = DriverManager.getConnection(url, "system", "oracle");
conn.setAutoCommit(false);
String query1 = "INSERT INTO WIN(NAME) VALUES('"+nameTextField.getSelectedText()+"')";
Statement stm = conn.createStatement();
stm.execute(query1);
JOptionPane.showMessageDialog(null, "Record Added Succesfully.", "Record Added",
JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
System.out.println(e);
}
}
nameTextField.getSelectedText()
I'm guessing that should be
nameTextField.getText()
Also, use a PreparedStatement for the SQL. You will less likely to make SQL syntax errors. Check out: geting data from multiple table when selecting a row then clicking a button for a basic example.
Im pretty sure the Jtextfield is the problem.
Well, learn how to do some basic debugging instead of guessing.
String query1 = "INSERT INTO WIN(NAME) VALUES('"+nameTextField.getSelectedText()+"')";
The above code can be written like:
String name = textField.getSelectedText();
// now you can verify the value of the name
System.out.println(name);
String query1 = "INSERT INTO WIN(NAME) VALUES('"+ name +"')";
// verify SQL syntax
System.out.println( query1);
Of course my first suggestion to use the PreparedStatement is easier, but learn how to display the value of variables when you do debugging.

Read a string with apostrophe from a JTextField and save it on a database

I have many JTextField objects and I want to read, in one of them, a string that contains apostrophes and then, this It will be saved on a database. The problem is when I try to save this string, because I obtain this error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'k')' at line 1
I put the apostrophe in a JTextField and the "k" letter is in the next JTextField. I can't understand if who can't read this kind of character is the database (I have a database written in SQL and I use MySQL), or the JTextField object. What can I do?
This is the code that save the strings caught from the JTextField objects (I get the strings into another method, simply using the method jTextField.getText();):
public void setNuovaAzienda(){
try {
int contCliente = 0;
Class.forName(NOMEDRIVER); //avvio il driver
conn = DriverManager.getConnection(SERVERURL, USER, PASSWORD);
Statement st = conn.createStatement();
Statement st1 = conn.createStatement();
Statement st2 = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT MAX(IdCliente) FROM cliente");
while (rs.next())
contCliente = rs.getInt(1);
contCliente++;
int showConfirmDialog = JOptionPane.showConfirmDialog(null,"Vuoi confermare l'inserimento del nuovo cliente?", "Conferma Inserimento", JOptionPane.YES_NO_OPTION);
if (showConfirmDialog == 0) {
try {
st1.executeUpdate("INSERT INTO cliente () VALUES ('"+contCliente+"', '"+citta+"', '"+indirizzo+"', '"+nCivico+"', '"+telefono+"')");
st2.executeUpdate("INSERT INTO personagiuridica () VALUES ('"+contCliente+"', '"+partitaIva+"', '"+nomeAzienda+"', '"+ragSociale+"', '"+fax+"')");
ImageIcon icon = new ImageIcon("C:\\Users\\salva\\Documents\\NetBeansProjects\\JavaApplication10\\src\\javaapplication7\\Icons\\icona v.png");
JOptionPane.showMessageDialog(null, "Cliente Inserito", "Conferma Inserimento", JOptionPane.INFORMATION_MESSAGE, icon);
InserisciOrdine linkInserisciOrdine;
linkInserisciOrdine = new InserisciOrdine();
linkInserisciOrdine.setLocationRelativeTo(null);
linkInserisciOrdine.setVisible(true);
dispose();
} catch (SQLException ex) {
Logger.getLogger(NuovaAzienda.class.getName()).log(Level.SEVERE, null, ex);
}
}
conn.close();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(NuovaAzienda.class.getName()).log(Level.SEVERE, null, ex);
}
}
contCliente, citta, indirizzo, etc. are global variable.
Sounds like you construct your SQL statements as a String, embedding the data directly, like
String dataString = ...; //get value from field
String sql = "INSERT INTO `mytable` (`col`) VALUES ('"+dataString+"')";
This is wrong, since if you have single quote in your string, this will result in invalid statement. Try outputting that string to System.out and executing it in the SQL worksheet, you should see what goes wrong. You should use Prepared Statements instead:
//Assuming you have jdbc Connection named conn
String dataString = ...; //get value from field
PreparedStatement ps = conn.prepareStatement("INSERT INTO `mytable` (`col`) VALUES (?)");
ps.setString(1, dataString);
ps.execute();
ps.close();
It will give you a decent protection against SQL injections as a bonus.
If you are unable to rewrite your code with prepared statements (e.g. legacy third-party API), then you should escape single quotes in your string, by replacing them with two single quotes (' -> '').
UPDATE
Indeed you do construct the statements using concatenation. AVOID THIS, unless you want to get hacked by a random script kiddie one day. Read about SQL injections, there's plenty of info, and they are one of the main vectors of hacker attacks.

SQL Exception: java.sql.SQLException: No data found

i get an error wherein it says SQL Exception: java.sql.SQLException: No data found, i cant seems to find the problem here. please help me, sorry for asking.
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:ict11";
Connection con = DriverManager.getConnection(url);
Statement statement = con.createStatement();
statement.executeUpdate( "DELETE from Employee where EmployeeID ="+txtId.getText()+"" );
statement.close();
con.close();
JOptionPane.showMessageDialog(rootPane, "Successfully Deleted");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
I can think about 2 issues
This could be because of unnecessary white spaces that getText() doesn't eliminate. Try txtId.getText().trim()
URL might be wrong.
Apart from that, do the following to improve the code.
Print complete stack trace
Use PreparedStatement instead of statement.
statement.executeUpdate( "DELETE from Employee where EmployeeID ="+txtId.getText()+"" );
try using this
statement.executeUpdate( "DELETE from Employee where EmployeeID ='"+txtId.getText()+"'" );
note the addition of single inverted comma at the start and end of txtId.getText()

Oracle Java SQL Exception Error: ORA-0094

I am trying to write a function for this button. I want to be able to pass it a textfield value and be able to go into my database to retrieve some information.....
Can somebody explain to me what is going on and provide me a solution to this madness?
Thank you all xD
I keep running into this stupid problem:
ACTION1 createdoracle.jdbc.driver.T4CConnection#484845aa
Exception:java.sql.SQLSyntaxErrorException: ORA-00904: "ART": invalid identifier
Code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//CLASS TYPE
//LIST ALL OFFERED CLASSES AND REVENUE
try{
String classtype = jTextField1.getText().trim();
if(classtype.equals("")){
JOptionPane.showMessageDialog(this, "Sorry Wrong input.... Please try again....");
}
else if(classtype != ""){
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection(
"jdbc:oracle:thin:#fourier.cs.iit.edu:1521:orcl",
"usr","pwd");
Statement stmt = conn.createStatement();
System.out.println("ACTION1 created"+conn+"\n\n");
String ct = jTextField1.getText().trim();
//String aa = "SELECT * FROM CLASS WHERE TYPE="+classtype;
//System.out.println(aa);
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE="+ct);
while (rset.next()) {
System.out.println(rset.getString("TITLE") + " ");
}
JOptionPane.showMessageDialog(this, "Class Type: "+classtype);
stmt.close();
conn.close();
System.out.println("Connection Closed");
}
catch(Exception sqle){
System.out.println("\nException:"+sqle);
}
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, "Please Retry input....", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Let me guess ... does the ct String start with "ART" (or some variation)?
If so, the problem is that SQL requires quotes around string literals. Your query probably looks to Oracle something like this:
SELECT * FROM CLASS WHERE TYPE=Art of War
but it should look like
SELECT * FROM CLASS WHERE TYPE='Art of War'
There are two ways to fix this:
Assemble the query with quote characters around ct.
Write the query as "SELECT * FROM CLASS WHERE TYPE=?", use a PreparedStatement instead of a Statement and use the setString method to supply the parameter value.
If done properly, the second approach is both more secure and more efficient. (The problem with string-bashing the query and using Statement is that you are potentially making yourself vulnerable to SQL injection attacks.)
You're passing the value as part of the query, and the string concatenation you're doing makes the SQL into:
SELECT * FROM CLASS WHERE TYPE=ART
(where ART is the value of ct from the textfield) so it's trying to find a column on the table called ART. At an absolute minimum you need to quote the string:
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE='" + ct + "'");
But really don't do this; as #Andreas_D says you're leaving yourself open to SQL injection. Always use prepared statements and bind variables:
String sql = "SELECT * FROM CLASS WHERE TYPE=?";
PrepareStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ct);
ResultSet rset = stmt.executeQuery();

Categories

Resources