i am trying to an integer field from the product table and trying to store in the originalQty variable but there is an error.How do i store the result in an int variabe
public int prodQty( String prodid){
int originalQty = 0;
try {
String sql="select QUANTITY from PRODUCT where productid='"+prodid+"' '";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
originalQty=rs.getInt(7);
}
}
catch (SQLException ex) {
}
System.out.println(originalQty);
return originalQty;
}
Use
originalQty=rs.getInt("QUANTITY");
And you have a quote too much in your query
... where productid='"+prodid+"' '";
^--------here. Remove that
If the input is a number you can remove the quotes entirely.
And you should actually use Prepared Statements that handle escaping inputs automatically and prevent SQL injections.
Some advice.
Always use column name.
Use prepared statement.
Learn how to debug your program. That will tell you exactly why the error.
Related
say I've got a JSON like this:
{"name": "tom", "id":1, "clothes":[{"shirt":"yellow"},{"shoes":black},.......]}
I'm trying to insert it, as is, into a column in a mysql DB using Java.
void insertVal(JsonObject json){
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Orders?user=root", "root", "1234");
Statement st = conn.createStatement();
StringBuilder values = new StringBuilder("(");
for (String key : json.keySet()){
if (key.equals("clothes")){
//do something to deal with this array
break;
}
values.append(json.get(key)).append(",");
}
values.append(")");
String insert = "INSERT INTO ORDERS VALUES " + values;
st.executeUpdate(insert);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This code works fine up to clothes key. So far, I've tried using JSON OBJECT and JSON MERGE but the format doesn't quite match, and I'd rather not parse right now.
So, is it possible to add clothes or do I have to parse it somehow? if so, what format would work best?
Thanks a lot
To all those concerned: The problem was the " string. mysql, and probably SQL in general, don't handle these well. There are two options. The first, and less recommended:
String parsed = json.get(key).toString().replace("\"", "");
Then, insert normally.
The second, much more recommended - use PreparedStatement. This way, you can write an insert/update query without minding the escape characters. Example, after i've inserted 'null' values for the clothes column:
PreparedStatement ps = conn.prepareStatement("UPDATE ORDERS set CLOTHES = ? WHERE ID = ?");
ps.setString(1, clothes); // clothes - get(key).toString()
ps.setInt(2, count); // count - counts which iteration we are
ps.executeUpdate();
I hope anyone in the future finds this useful.
When trying to pull from an SQL database, I get in Java console.
I am able to enter my ID manually in the prepareStatement, but I can't use setString to work with with the prepareStatement.
I haven't throught of too much to try, but I did find that the issue is within the while statement. rs.next returns false when it should return true. The information in SQL has been committed, and I can call all of the information in java using a function that reads out the entire table.
getemployeeDataById("01");
private static void getemployeeDataById(String e_id) {
DBConnection dbConnection = DBConnection.getInstance();
PreparedStatement ps;
try {
ps = dbConnection.getConnection().prepareStatement("select * from employee where E_ID = ?");
ps.setString(1, e_id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("ename"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
SQL
CREATE TABLE EMPLOYEE
(E_ID CHAR(3) PRIMARY KEY,
ENAME CHAR(25),
DOB CHAR(25),
EMAIL CHAR(25),
PHONE CHAR(25),
ADDRESS CHAR(25));
INSERT INTO EMPLOYEE
VALUES
('01','JEREMY MANN','12/23/1992','jeremy#jeremy.com','317-528-1234','123 CandyCane Lane');
I am expecting to get the name outputted in the console, so for this example it would be "JEREMY MANN." The code runs and then in the Eclipse Java console it shows Application [Java Application]. It runs into an issue within the while statement, but I'm not sure what's causing rs.next to be false.
In Oracle 11g (well, Oracle versions generally) CHAR is a fixed width type, and if you give it a value shorter than the given width, it will be padded with blanks (which might not be obvious if you just dumped the table contents). In this case, your key is length 3, but the string "01" is length 2, so that won't work.
Try VARCHAR2 for the column types, that's a variable length string.
Code snippet:
On a button click, actionevent will be called
public void actionPerformed(ActionEvent e)
{
Function f = new Function();
Function is a nested class which i have used to establish the connection with the database.
The code snippet for function class is also provided in the end.
ResultSet rs = null;
String Cid ="cust_id";
String Pno="cust_phone";
String cat="cust_cat";
String start_date="st_date";
String Adv_amt="adv";
String Adv_end="end_date";
String Address="addr";
t2 is the Textfield name which i have used to get entry of customer name. I want to use this customer name as a PK to fetch all the other data about that customer from DB.
rs=f.find(t2.getText());
try{
if(rs.next())
{
t1.setText(rs.getString("cust_id"));
t3.setText(rs.getString("cust_phone"));
t4.setText(rs.getString("cust_cat"));
t5.setText(rs.getString("st_date"));
t6.setText(rs.getString("adv"));
t7.setText(rs.getString("end_date"));
t8.setText(rs.getString("addr"));
}
else
JOptionPane.showMessageDialog(null,"No data for this name");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
Here is the code snippet for nested class Function which is inside the main class:
class Function{
Connection con=null;
ResultSet rs= null;
PreparedStatement ps = null;
public ResultSet find(String s)
{
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#Localhost:1521:xe","system","qwerty");
ps= con.prepareStatement("Select * from gkkdb where cust_name='?'");
ps.setString(1,s);
rs= ps.executeQuery();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return rs;
}
}
Please help figure out the problem.
Don't put the parameter placeholder ? in single quotes.
This:
ps = con.prepareStatement("Select * from gkkdb where cust_name='?'");
should be
ps = con.prepareStatement("Select * from gkkdb where cust_name = ?");
The ? is not recognized as a placeholder if you enclose it in single quotes.
Sorting out the bind variable will fix your immediate issue.
You should explicitly specify what columns you want selected and that way you'll only get what you need (someone might add a BLOB column later) and you'll get them in the right order (someone might change the table create script before running on another DB instance, although you are looking up the columns by name, a different order would only impact if you were using positional indexes).
Ditto on the other answer re: bind variables (i.e. no quotes)
Plus, "select * from" is never a good idea, ask your DBA.
Obviously your code is for example, but you should make sure you free up any resources (Connection, Statement, ResultSet) as soon as they are done with. Use Java 7 try-with-resources.
I'm new to working with JDBC commands. I have a database in MYSQL and each entry gets an ID. As initially created the ID was just a static variable that I iterated when the constructor runs. This was okay until I started deleting entries or running the program a second time. Then I start getting collisions. I need a way to return the highest row in the table and assign it to an integer that I can iterate.
The QuerySELECT MAX(ID) FROM table seems to get the value that I'm looking for. But I'm not sure of the syntax to get that value into an integer so I can return it.
public int getHighestRow() {
PreparedStatement ps;
int highestID = 0;
try {
ps = getSQLDB().prepareStatement("SELECT MAX(studentID) FROM student");
ps.execute();
} catch (SQLException e){
Logger.getLogger(Undergraduate.class.getName()).log(Level.SEVERE, null, e);
}
if (highestID > 0) return highestID;
else return 0;
I have a feeling this is very simple, but I wasn't able to find an existing answer. Or is there a more elegant way to do this in general?
SQL of different providers solve the retrieval of automatic generated keys differently. JDBC provides a standard solution.
Better use this JDBC solution, as it prevents mixing up those keys when insertions are done at the same time.
try (PreparedStatement ps = getSQLDB().prepareStatement(
"INSERT INTO student(....) VALUES(?, ..., ?)",
Statement.RETURN_GENERATED_KEYS)) { // Without StudentId
ps.setString(1, name);
...
ps.executeUpdate();
try (ResultSet rsKeys = ps.getGeneratedKeys()) {
if (rsKeys.next()) { // Only one record inserted
int studentId = rsKeys.getInt(1); // One key generated
}
}
} catch (SQLException e){
Logger.getLogger(Undergraduate.class.getName()).log(Level.SEVERE, null, e);
}
The mechanism with try(...). try-with-resources, ensures that close is called automatically.
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.