SQL syntax error for my java program - java

My code :
try{ Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lentele", "root", "");
String select = "SELECT * FROM darbuotojai WHERE 1";
String ID = infoID.getText();
String Vardas = infoV.getText();
String Pavardė = infoP.getText();
String Pareigos = infoPar.getSelectedItem().toString();
String Alga = infoAlg.getText();
String Premija = infoPre.getText();
String insert = "INSERT INTO `darbuotojai`(`ID`, `Vardas`, `Pavardė`, `Pareigos`, `Alga`, `Premija`) VALUES ('"+ID+"','"+Vardas+"','"+Pavardė+"','"+Pareigos+"','"+Alga+"','"+Premija+"',)";
stm.executeUpdate(insert);
JOptionPane.showMessageDialog(null, "Užklausa sėkminga");
infoID.setText("");
infoV.setText("");
infoP.setText("");
infoPar.setSelectedItem("");
infoAlg.setText("");
infoPre.setText("");
display();
} catch (Exception e) {JOptionPane.showMessageDialog(null, e.getMessage()); }
And i get errors like this:
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 ')' at line 1.
And ones more: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user ''#'localhost' to database 'lentele'.
Please, explain these problems for beginner in the easiest way.
This code is for the add button, which would help to insert info into my table.

Remove the comma before your closing bracket:
Premija+"',)";
becomes
Premija+"')";
Except don't build your query by hand, unless you want to be vulnerable to SQL injection attacks: use a PreparedStatement.

Related

updating mysql db using java program

I am trying to add a new row in my table inside mysql db , i tried to use executeUpdate(); and executeQuery(); but both did not work, I am taking columns values from multiple JTextField and adding every one of them to a single Librarian object and then i call setLibrarian() method in main.
But I get the following error message:
java.sql.SQLException: 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 '#gmail.com , 14 , cairo , 4.6565486E7 )' at line 1
here is my code:
public static void setLibrarian(Librarian lib){
Connection con = null;
Statement st = null;
String dbURL = "jdbc:mysql://localhost:3306/universitysystem";
String username = "root";
String password = "";
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbURL , username , password);
st = (Statement) con.createStatement();
st.executeUpdate("INSERT INTO librarians(username , password , email , address , city , contactno)"
+ " VALUES("+lib.getName()+" , "+lib.getPassword()+" , "+lib.getEmail()+" , "+lib.getAddress()+" , "+lib.getCity()+" , "+lib.getContactNo()+" ); ");
con.close(); //closing connection
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
}
}
You have a security leak, you must never put user input into a query statement like this. What if someone enters as password:
thisIsMyPassword'; DROP TABLE librarians CASCADE; EXECUTE 'FORMAT C: /force'; --
You'd be quite screwed.
The proper answer is PreparedStatement, which lets you write a single constant as a query (INSERT INTO librarians(...) VALUES (?, ?, ?, ?) - with the question marks) and then provide the value for each question mark separately, and then you're safe from the above issue (then that will simply be their password, verbatim).
This, in passing, also fixes your problem here, which is either that the double isn't working out, or more likely that there are ' symbols in that gmail address.
While you're at it, look at 'try with resources java', because the way you are closing your connections isn't safe either and results in memory leaks. Finally, exception handling with e.printStackTrace() is broken. Fix your IDE; the proper 'I do not care' content is throw new RuntimeException("Uncaught", e); - what you are doing results in many errors and code in unknown states (also a security issue).

Read results from H2DB

I have a problem with reading the content of the rows in the database.
I want to show the information (in the console for the moment) about the employee with given position and name. I have built the path ,started the database in H2 but I am not sure I have used PreparedStatement right .
Table "MyTable" not found
I removed the try/catch to be more readable.
static public void Search (JButton a , JFormattedTextField name, JComboBox<String> b ) {
a.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e ) {
Connection con = null;
con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test" + "sa" + "");
Statement stm = null;
String ime = name.getText();// reads the name
String poz = (String) b.getSelectedItem();// reads the position
Class.forName("org.h2.Driver");
String sql1 = String.format("SELECT * FROM RABOTNICI WHERE IME = '%s' OR POZICIA = '%s'", ime, poz);
PreparedStatement prstm = null;
prstm = con.prepareStatement(sql1);
ResultSet rs = null;
rs = prstm.executeQuery(sql1);
}
});
}
jdbc:h2:tcp:...
You are using TCP connection but not starting H2 TCP server like this:
http://www.h2database.com/html/tutorial.html#using_server
Normally H2 database is used as embedded without TCP server like this:
http://www.h2database.com/html/tutorial.html#connecting_using_jdbc
jdbc:h2:/path/to/dbfile
I think you had some sources of information and something went wrong down the way.
The way you created a preparedStatement, even if it's parsed correctly, is prone to SQL Injections.
You should first create the statement and only then inject the values.
String sql1 = "SELECT * FROM RABOTNICI WHERE IME = ? OR POZICIA = ?"
PreparedStatement prstm = con.prepareStatement(sql1);
prstm.setString(1, ime);
prstm.setString(2, poz);
Please consult this doc page for correct usage of PreparedStatements
Also, getConnection's argument looks a bit messed up.
con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test" + "sa" + "");
The following line should appear before the connection creation.
Class.forName("org.h2.Driver");
I suggest using this tutorial for instruction regarding connection to H2 DB
And last, I'm not sure how do you get the error about "MyTable" its never mentioned in your code snippet.
My code quotes were not tested but I believe are clear enough to get the idea.

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.

MySQL SyntaxErrorException about UPDATE query

I am trying to update a field in my table using Netbeans. The update statement is as follows:
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/student_reg";
try {
Class.forName(driver);
Connection con = DriverManager.getConnection(url,"user","abc");
PreparedStatement state = con.prepareStatement("UPDATE supplier SET sname='" + txtname.getText()+"' , add='"+txtadd.getText()+"' WHERE sid ='" +txtid.getText() + "'");
state.executeUpdate();
JOptionPane.showMessageDialog(null, "Your Record sucessfully Updated");
}catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
but I am getting the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQL SyntaxErrorException:
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 'add=kegalle'where sid=001" at line 1
How can I solve it?
You need to escape reserved words in MySQL like add with backticks
UPDATE supplier
SET sname='" + txtname.getText()+"', `add` = ...
here ---------------^---^
BTW you are not using prepared statement correctly.
The problem seems to be the way you're using PreparedStatement. Try this:
PreparedStatement state = con.prepareStatement("UPDATE supplier SET sname = ?, add = ? WHERE sid = ?");
state.setString(1,txtname.getText()); // sname (parameter 1)
state.setString(2,txtadd.getText()); // add (parameter 2)
state.setString(3,txtid.getText()); //sid (parameter 3) is actually a varchar?
state.executeUpdate();

Wanting to insert for the first time in database and getting an error

So this is my code
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/test";
//ResultSet rs = null;
PreparedStatement psmnt = null;
//FileInputStream fis;
connection = DriverManager.getConnection(connectionURL,"root","123");
psmnt = connection.prepareStatement("insert into Table1 (name, desc, r,g,b," +
"varR,varG,varB,skewnessR,skewnessG,skewnessB)values(?,?,?,?,?,?,?,?,?,?,?)");
final String text2 = setName.getText();
final String text3=setDesc.getText();
psmnt.setString(1,text2);
psmnt.setString(2,text3);
psmnt.setString(3,stringMeanR);
psmnt.setString(4,stringMeanG);
psmnt.setString(5,stringMeanB);
psmnt.setString(6,stringVarianceR);
psmnt.setString(7,stringVarianceG);
psmnt.setString(8,stringVarianceB);
psmnt.setString(9,stringSkewnessR);
psmnt.setString(10,stringSkewnessG);
psmnt.setString(11,stringSkewnessB);
//fis = new FileInputStream(f);
//psmnt.setBinaryStream(2, (InputStream)fis, (int)(f.length()));
int s = psmnt.executeUpdate();
psmnt.close();
connection.close();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else {
System.out.println("Unsucessfull to upload image.");
}
The problem is that i get the following 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 'desc, r,g,b,varR,varG,varB,skewnessR,skewnessG,skewnessB)values('','','105.59 , ' at line 1
desc is a reserved SQL keyword (used in order by foo desc). Change the name of the column you named "desc" (or escape it using backticks, but I would change the name to make it easier)
desc is a reserved keyword in SQL for describing an SQL table. As a result, if your column name is 'description' then it should be 'description'; not 'desc' as desc is reserved in MySQL for describing the table itself or showing the SQL code for the creation of the table.

Categories

Resources