Query JDBC Java - java

I have a problem with my java/jdbc code.
parameter index out of range (2 number of parameters which is 1)
Code:
Connection c = null;
MySQL MySQL = new MySQL(Host, Port, Database, Username, Password);
c = MySQL.open();
Player player = (Player) sender;
String zapytanie = "UPDATE `?` SET `tag`=? WHERE `name`='?';";
PreparedStatement ps = c.prepareStatement( zapytanie );
ps.setString(1, Tabel);
ps.setString(2, red);
ps.setString(3, player());
ps.executeUpdate(); //Executes the query
ps.close(); //Closes the query
c.close();

final String zapytanie = "UPDATE " + Table + " SET tag = ? WHERE name = ?";
No quotes around ? required
JDBC doesn't require a ; after any SQL statement
Place holders ? can only be used for column values

Related

Update data in table

The thing i want to achieve here is that i have a table name total_product in mysql database and i want to retrieve the value of SNo = 1 from the table and update the Quantity in the table.
There is a text box i am using in GUI in which the additional product produced will be written.
The output from the table is stored in variable id and the new quantity that is produced is stored in the variable q1.
so the new product quantity will be q1 = q1 + id.
I am not able to understand what should i put in the sql statement that is used in stmt.executeUpdate(sql) because the sql is a string and i have to pass an integer value to Qunty in the sql string.
Please Help.
Connection conn = null ;
Statement stmt = null ;
String url = "jdbc:mysql://localhost:3306/project";
String user = "root";
String password = ".dpadpep";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
String sql = "Select Qunty from total_product " + "where SNo = 1";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int id=0;
int q1 = Integer.parseInt(fld1[0].getText());
while(rs.next()) {
id = rs.getInt(1);
System.out.println("Quantity="+id);
}
q1 = q1+id;
sql = "UPDATE total_product " + "set Qunty = q1 where SNo=1";
stmt.executeUpdate(sql);
You don't need to explicitly retrieve the current value in the database, you can simply add the additional amount directly:
int q1 = Integer.parseInt(fld1[0].getText());
String sql = "UPDATE total_product SET Qunty = Qunty + ? WHERE SNo = 1";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, q1);
ps.executeUpdate();

Getting java.sql.SQLException: No value specified for parameter 1 while updating record in servlet using mysql

I am getting java.sql.SQLException:
No value specified for parameter 1 error
while updating email address which is 11th column in database.
This is the code:
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3308/authenticate", "root", "root");
st = con.createStatement();
String query = "update custt set email =? where accno =?";
PreparedStatement ps = con.prepareStatement(query);
ps.executeUpdate();
System.out.println("updated");
//st.executeUpdate(query);// create a statement
ps.setInt(2, acn);
ps.setString(11, eml);
//eml=rs.getString(11); // set input parameter 1
System.out.println("updated value"+acn);
System.out.println("updated value"+eml);
// acnn = rs.getInt(2);
/// session.setAttribute("Accno", acnn);
//session.setAttribute("C_email", eml);
// System.out.println("updated");
} catch (SQLException ex) {
Logger.getLogger(UpdateDetails.class.getName()).log(Level.SEVERE, null, ex);
}
you are executing the statement before you pass the parameters.
This is how it should look like.
String query = "update custt set email =? where accno =?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, eml);
ps.setInt(2, acn);
ps.executeUpdate();
System.out.println("updated");
The first parameter is always index 1 and the second parameters is index 2, etc regardless of the order of columns in database.

How to do INSERT SELECT INTO in Java using PrepareStatement

I'm trying to do an INSERT INTO SELECT which are inserting into in 1 table by selecting specific data in columns from 2 tables. The thing is, it will involve with user input from JTextField as well. I have searched for many solutions but still got an error and I just dunno what else to do. I'm using Java as PL and Oracle as DB. This is what I have got so far :
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","ghost","slayer");
stmt = con.createStatement();
String sbjC = sbjCode.getText(); //textfield for subjectCode
String sbjN = sbjName.getText(); //textfield for subjectName
String matricsno = textstudentid.getText(); //textfield for matrics number
String sbjG = sbjGrade.getText(); //textfield for subjectGrade (not gonna be use in db, just for comparison)
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = '"+sbjC+"' AND b.subjectName = '"+sbjN+"' AND s.matricsNo = '"+matricsno+"'";
/* table Transferred has 5 column which are subjectCode,subjectName,credit,prequisite,matricsNo [matricsno as FK]
* table bitm has 5 column [subjectCode as PK]
* table student has 6 column [matricsno as PK]
*/
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, "SELECT credit FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(4, "SELECT prequisite FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(5, "SELECT matricsno FROM student WHERE matricsno = '"+matricsno+"'");
ps.executeUpdate(sql1);
The only error I have got after executing and insert all data needed into JTextField is java.sql.SQLException : Invalid column index.
The SQL statement has been test in SQL Developer and succeed. Just I'm bit confused on how to do it on Java.
Thank you for all of your response and time.
I'm a newbie in Java.
For PreparedStatement, you'd code ? Into the sql and later replace that with values.
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ? ";
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3,matricsno);
ps.executeUpdate ();
This should do it.
Your error came from giving parameters (setString...) without matching ?
Unfortunately you absolutely misunderstood what the preparedStatemet does.
You have to write ? -s into the query and the preparedSatement is going to replace it on a typed way:
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ?";
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, matNo);
ps.executeUpdate();
To answer my own question, I'll put comment on the changes that I have made to the code and make it work:
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","aza","jaiza");
stmt = con.createStatement();
String sbjC = sbjCode.getText();
String sbjN = sbjName.getText();
String matricsno = textstudentid.getText();
String sbjG = sbjGrade.getText();
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ?"; // from textfield to ?
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, matricsno);
//from all the SELECT statement to just 3 user-input-from-textfield column
ps.executeUpdate(); // remove the sql1 in ps.executeUpdate(sql1);

Where should ? be placed in a PreparedStatement? [duplicate]

This question already has an answer here:
Having a Column name as Input Parameter of a PreparedStatement
(1 answer)
Closed 7 years ago.
I am using PreparedStatement to select records from a table:
public static String getMemberInfo(String columnName, Integer memberId) {
String memberInfo = "";
String sql = "SELECT ? FROM member WHERE member_id = ?";
DatabaseConnector.setConn();
try(Connection conn = DatabaseConnector.getConn();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, columnName);
ps.setInt(2, memberId);
try(ResultSet rs = ps.executeQuery()) {
if(rs.next()) {
memberInfo = rs.getString(columnName);
}
}
} catch(SQLException se) {
se.printStackTrace();
}
return memberInfo;
}
When I use
SELECT " + columnName + " FROM member WHERE member_id = ?, it works.
But when I use
SELECT ? FROM member WHERE member_id = ?, it does not.
Where should ? be placed in prepared statements?
? is for input values (typically in the WHERE clause conditions).
? is not for selected columns.
Column name must be hard-coded, Only column values can be set using ?.
but you can set dynamic column name by doing something like this :
String sql = "SELECT "+ columnName +" FROM member WHERE member_id = ?";

Unable to insert values in SQLite3 database using JDBC

I have the following JDBC code , in which I am not getting any error, but unfortunately the data is not being added to the database. The code that I am using is :
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:../../clientDb.db");
c.setAutoCommit(false);
String expenseUUID = UUID.randomUUID().toString();
expenseUUID = expenseUUID.replaceAll("-", "");
String sqlQuery = "insert into expense (expenseUUID , user_id,expense_description,
total_amount, place, per_exp_flag, category " +
",creation_date ) values (?,?,?,?,?,?,?,?) ";
ps = c.prepareStatement(sqlQuery);
ps.setString(1, expenseUUID);
ps.setInt(2, user_id);
ps.setString(3, description);
ps.setInt(4, total_amount);
ps.setString(5, place);
ps.setInt(6, 1);
ps.setInt(7, category);
ps.setString(8, creation_date);
int result = ps.executeUpdate();
if(result == 1){
b = true;
}
What is the error ? When I tried using select statement , I got the result in the result set, But why is it not inserting anything? I am getting '1' in
int result = ps.executeUpdate();
What is possibly the error? I am using SQLite3 as back-end database.
You have c.setAutoCommit(false); so your INSERT won't actually be written to the database until you c.commit();. Add that statement after the ps.executeUpdate().

Categories