How to write prepareStatement in Java - java

i want to use getParameter to get in Strings and ints and put them in a database using prepareStatement and SQL. It gives me errors with setString and setInt.
try {
String id = request.getParameter("clientid");
String cname = request.getParameter("clientname");
String address = request.getParameter("address");
String phonemodel= request.getParameter("phonemodel");
String imei = request.getParameter("imei");
String problem = request.getParameter("problem");
String date2 = request.getParameter("date");
String comments1= request.getParameter("comments");
int clientid = Integer.parseInt(id);
int imeino = Integer.parseInt(imei);
// int date1 = Integer.parseInt(date2);
Statement pstmt;
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app" , "app");
pstmt=con.prepareStatement("Insert into movilapp(id,clientname,address,modle,imei,problem,date,comments) values(?,?,?,?,?,?,?,?)");
pstmt.setInt(1,clientid);
pstmt.setString(2,cname );
pstmt.setString(3,address);
pstmt.setString(4,phonemodel);
pstmt.setInt(5,imeino);
pstmt.setString(6,problem);
pstmt.setString(7, comments1);
pstmt.executeUpdate();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}

You called con.prepareStatement to get a PreparedStatement, but then you assigned it to a variable of type Statement, so Java doesn't know that there is a PreparedStatement-specific method setString.
Assign it to an actual PreparedStatement variable, by changing the declaration type of pstmt from
Statement pstmt;
to
PreparedStatement pstmt;

*IF Use Statement Then its syntax is *
Statement stmt = null;
stmt = conn.createStatement( );
String sql = "UPDATE Employees set age=30 WHERE id=103";
stmt.executeUpdate(sql);
And for PreparedStatement it is
PreparedStatement pstmt = null;
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
psmt.setInt(1,30);
psmt.setInt(2,1003);
psmt.executeUpdate(SQL);
So change Statement pstmt; to PreparedStatement pstmt = null; And it will work.

Related

Prepared statement execute query error (com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException)

I have written a simple method to get a string out of the database:
public String getUserString(int id, String table, String column) {
String output = null;
try {
String sql = "SELECT ? FROM ? WHERE id=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setString(1, column);
preparedStatement.setString(2, table);
preparedStatement.setInt(3, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
} catch (SQLException e) {
e.printStackTrace();
}
return output;
}
But when I try to use it like this: coreMySQL.getUserString(1, "economy", "balance");
I get this error:
https://pastebin.com/BMAmN4Xh
You can't set table name and column names with setXxx method(s) for PreparedStatement. It can only be used to set the values.
However, you can do a simple String replace to substitute table names and column names, e.g.:
String query = SELECT <column> FROM <table> WHERE id=?;
String sql = query.replaceAll("<column>", column).replaceAll("<table>", table);
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
Define a query template as:
String queryTemplate = "SELECT %s FROM %s where id = ?;";
// Inside Function:
PreparedStatement preparedStatement = getConnection().prepareStatement(String.format(template, column, table));
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();

How to retrieve values from SQL when ID is in array form

The function below will pick the highest value and it will display value which are in column place1(in table placeseen) as output based on the ID.So far I only can get the highest value but not the value in place1.
I don't know what's wrong with my coding because the output is always shows empty.
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0+1];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
String sql ="Select* from placeseen where ID =aa[i]";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
ps.close();
rs.close();
conn.close();
}
}
System.out.println(highest);
}
instead of
String sql ="Select * from placeseen where ID =aa[i]";//aa[i] taking a value
use
String sql ="Select place1 from placeseen where ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]);
passing aa[i] variable value .
Avoid sql injection
You can try this
// as you are using preparedStatement you can use ? and then set value for it to prevent sql injection
String sql = "Select * from placeseen where ID = ?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]); // 1 represent first attribute represented by ?
System.out.println(ps); // this will print query in console
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println("Inside rs.next()"); // for debug purpose
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
// remaining code

ResultSet not open. Operation 'moveToInsertRow' not permitted. Verify that autocommit is OFF

i'm having a trouble with this error, when i clicked the button, it'll take the values of the labels and put it in the table from database
void showAll(){
try{
rs1 = stmt.executeQuery("SELECT * FROM BORROW_RETURN");
while(rs1.next())
{
String bookpp = rs1.getString("name");
String emailse = rs1.getString("email");
String booktee = rs1.getString("book_title");
String ser_no = rs1.getString("serial_no");
String borr = rs1.getString("borrowed");
String ret = rs1.getString("return");
loginModel3.addRow(new Object[]{bookpp, emailse, booktee, ser_no, borr, ret});
}}catch(SQLException err){
System.out.print(err);
}
}
and this is the connection to the connection to the database
void DoConnect1( ) {
try{
String host = "jdbc:derby://localhost:1527/Dafuq7";
String uName ="Dafuq7";
String uPass ="Dafuq7";
con = DriverManager.getConnection(host, uName, uPass);
//EXECUTE SOME SQL AND LOAD THE RECORDS INTO THE RESULTSET
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM borrow_return";
rs1 = stmt.executeQuery(sql);
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
}
and upon clicking the button the said error occurs,
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String ema = jLabel20.getText();
String enm = jLabel21.getText();
String booknm = bttl.getText();
String snnnn = sernum.getText();
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dates = dateFormat.format(date_borr.getDate());
try {
rs1.moveToInsertRow();
rs1.updateString( "book_title", booknm );
rs1.updateString( "serial_no", snnnn );
rs1.updateString( "name", enm );
rs1.updateString( "email", ema );
rs1.updateString( "borrowed", dates );
JOptionPane.showMessageDialog(null, "HAHA");
loginModel3.addRow(new Object[]{names, booknm, snnnn, enm, ema, dates});
con.setAutoCommit(false);
System.out.println(con.getAutoCommit());
rs1.insertRow( );
stmt.close();
rs1.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM accounts";
rs1 = stmt.executeQuery(sql);
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
}
You are setting autoCommit to false after your queries are really committed. You need to set it false once after you open connection or before start executing your queries.
con = DriverManager.getConnection(host, uName, uPass);
//EXECUTE SOME SQL AND LOAD THE RECORDS INTO THE RESULTSET
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM borrow_return";
con.setAutoCommit(false);
rs1 = stmt.executeQuery(sql);
https://codedump.io/share/WK0Jtw7GEH3h/1/why-do-i-get-javasqlsqlexception-resultset-not-open-operation-39next39-not-permitted-java-derby-database
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

How to use java variable to insert values to mysql table?

Hi i am trying to insert the values in to mysql table. i am trying this code.
i have assigned values to variable and i want to pass that variable to that insert statement.
Is this correct?
code
int tspent = "1";
String pid = "trng";
String tid = "2.3.4";
String rid = "tup";
String des = " polish my shoes!";
INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');
here is what i have tried, but i am not able to insert values
try
{
conn=DBMgr.openConnection();
String sqlQuery = "INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');";
st = conn.createStatement();
rs = st.executeQuery(sqlQuery);
}
You should use executeUpdate() method whenever your query is an SQL Data Manipulation Language statement. Also, your current query is vulnerable to SQL Injection.
You should use PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\
Then set the variables at those index:
pstmt.setString(1, pid);
// Similarly for the remaining 4
// And then do an executeUpdate
pstmt.executeUpdate();
Try this,
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String uname="username";
String pass="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,uname,pass);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"')");
Use a PreparedStatement and set the values using its setXXX() methods.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO `time_entry`
(pid,tid,rid,tspend,description) VALUE
(?,?,?,?,?)");
pstmt.setString(1, pid );
pstmt.setString(2, tid);
pstmt.setString(3, rid);
pstmt.setInt(4, tspent);
pstmt.setString(5,des );
pstmt.executeUpdate();
import java.sql.*;
class Adbs1{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rk","root","#dmin");
//here rk is database name, root is username and password
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into emp values('rk11','Irfan')");
// stmt.executeUpdate("delete from emp where eid ='rk4'");
//stmt.executeUpdate("update emp set ename='sallu bhai' where eid='rk5'");
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

how to insert variable into a table in MySQL

I know how to add data into a table. Like
String insertQuery = "INSERT INTO tablename (x_coord, y_coord)"
+"VALUES"
+"(11.1,12.1)";
s.execute(insertQuery);
11.1 and 12.1 can be inserted into table. Now given a float variable
float fv = 11.1;
how to insert fv into the table?
In JAVA, you can use prepared statements like this:
Connection conn = null;
PreparedStatement pstmt = null;
float floatValue1 = 11.1;
float floatValue2 = 12.1;
try {
conn = getConnection();
String insertQuery = "INSERT INTO tablename (x_coord, y_coord)"
+"VALUES"
+"(?, ?)";
pstmt = conn.prepareStatement(insertQuery);
pstmt.setFloat(1, floatValue1);
pstmt.setFloat(2, floatValue2);
int rowCount = pstmt.executeUpdate();
System.out.println("rowCount=" + rowCount);
} finally {
pstmt.close();
conn.close();
}
I recommend you use a Prepared Statement, as follows:
final PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO tablename (x_coord, y_coord) VALUES (?,?)");
stmt.setFloat(1, 11.1f);
stmt.setFloat(2, 12.1f);
stmt.execute();

Categories

Resources