Update one row using sql in jsp - mysql

I am trying to update column "Name" in table "changerequest":
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ccb-dbf", "root", "1234");
String N= name;
String yy="Accepted";
Statement st2= con.createStatement();
st2.executeUpdate("UPDATE changerequest SET Status="+yy+"Where Name="+N);
What is the syntax error here?

Variable yy and N both are String so after concatenation your query
UPDATE changerequest SET Status=AcceptedWhere Name=someName
No space between Accepted and Where, Which is not a valid sql query.
Try
String query = "UPDATE changerequest SET Status = " + yy + " Where Name = " + N;
Statement st2= con.createStatement();
st2.executeUpdate(query);

try this one:-
st2.executeUpdate("UPDATE changerequest SET Status=" +yy+ " Where Name="+N);
Note:make a space between set status=? and where clause

Related

ResultSet make an error [duplicate]

This question already has an answer here:
insert query with varchar as data type for primary key
(1 answer)
Closed 8 years ago.
hello i have a problem with this resultset.
public ResultSet seleccionar(String id, String pass) throws SQLException {
PreparedStatement stmt;
String consulta = "SELECT iduser from personas ";
consulta+= " WHERE nombre=?";
consulta+= " AND pass= ?";
objetoConexion = Conexion.getInstance().getConnection();
stmt = objetoConexion.prepareStatement(consulta);
stmt.setString(1,id);
stmt.setString(2,pass);
ResultSet rs = stmt.executeQuery(consulta);
rs.first();
return rs;
this is my error
.mysql.jdbc.exceptions.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 '? AND pass= ?' at line 1
You need to check you spaces on your String consulta.
Have you considered using a StringBuffer and logging your SQL statements to the console so you can see what the queries look like?
You have to put a space before AND.
String consulta = "SELECT iduser from personas ";
consulta+= " WHERE nombre='?";
consulta+= "' AND pass='?'";

How to use last_insert_id() with "ADODB.Connection" object correctly?

I'm having a problem in retrieving last record id from database. This code below, is the closer I can get. But still, it return record id, as 0; ,then when I execute again, it will return, record of previous execute, not the current one.
sql = "insert into program (prog_det,budget,prog_obj,outcome,target_group,awareness,engagement,issue,seq_no) value ('"&prog_title&"','"&prog_budget&"','"&prog_obj&"','"&prog_result&"','"&prog_target&"','"&prog_aware&"','"&prog_involment&"','"&prog_issues&"','99');"
sql2 = "select last_insert_id() as last_id"
set kpi_prog_conn=Server.CreateObject("ADODB.Connection")
set kpi_prog_rs=Server.CreateObject("ADODB.Recordset")
kpi_prog_conn.Open ObjConn
kpi_prog_conn.Execute(sql)
kpi_prog_conn.Open sql2,objConn,adLockPessimistic
response.write kpi_prog_rs("last_id")
Your penultimate line looks wrong
Try
kpi_prog_rs.Open sql2,kpi_prog_conn,adLockPessimistic
IS the ID you are trying to retrieve is the Primary key of the corresponding table? Try using Scope_Identity() instead of last_insert_id()
Query - SELECT SCOPE_IDENTITY() AS [LAST_IDENTITY]
It returns you the last inserted id into the table
I don't have mysql but try:
sql2 = "select last_insert_id() as last_id;"
sql = "insert into program (prog_det,budget,prog_obj,outcome,target_group,awareness,engagement,issue,seq_no) value ('"&prog_title&"','"&prog_budget&"','"&prog_obj&"','"&prog_result&"','"&prog_target&"','"&prog_aware&"','"&prog_involment&"','"&prog_issues&"','99');" & sql2
set kpi_prog_conn=Server.CreateObject("ADODB.Connection")
kpi_prog_conn.Open ObjConn
set kpi_prog_rs = kpi_prog_conn.Execute(sql)
anotherRecordset = kpi_prog_rs.NextRecordset
response.write anotherRecordset("last_id")

Having problems crafting SQL statements to get tables and values in JSP

conn = DriverManager.getConnection(connURL);
String sqlStr = "Select * from inventory where functions" + "like ? order by brand, model";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setString(1, "%" + search + "%");
ResultSet rs = pstmt.executeQuery();
Hi guys, i am having error with this code at line 2 and line 4. I believe that my coding contains errors.
I have a doubt that my SQL query is not correctly formatted. The pstmt.setString will set the search value to the ? in the SQL query.
The error:
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 ''%null%' order by brand, model' at line 1
The syntax of your sql query declaration is wrong. That is why you're getting that error. Why are you including + in between ?
Try
conn = DriverManager.getConnection(connURL);//this is bad use a connection pool
StringBuilder sb = new StringBuilder().append("Select * from inventory where functions");
sb.append(" like ? order by brand, model");
String sqlStr = sb.toString().intern();//use intern if this function is used many times

Error query with single quote

I have problem with single quotes in my query:
myquery =" select x from sometable where x = 'abc' ";
String enc = URLEncoder.encode(myquery, "utf-8");
The result in enc: x%3D%27abc%27
Then I use HTTP Connection to parse myquery with php file//. I get the error:
Errorquery: select x from sometable where x =\'abc\'
Is there problem with myquery (single quotes/'abc')?

PreparedStatement: Can I supply the column name as parameter?

Let's say I have a table with 3 columns: C1, C2, C3
I make a search based on the C1 column.
Could I make something similar like this (this is not working - because this is not the way prepareStatement it's used:) )
String c;// the name of the column
...
String sql = "select * from table where ? = ?";
pre = con.prepareStatement(sql);
pre.setString(1, c);
pre.setString(1, i);
rs = pre.executeQuery();
The main idea, I don't want to have 3 ifs for every column. An elegant solution?
This won't work. The prepare statement parses the SQL, sends to the database for validation and compilation. If question marks could substitute parts of the SQL, you would loose the whole point of bound variables - speed and security. You would reintroduce SQL injection back and statements will have to be recompiled for all parameters.
Wouldn't something like SELECT * FROM table WHERE c1 = ? OR c2 = ? OR c3 = ? be better (of course depending on indexes and table sizes).
you could code up a a set of sql queries and store them in a map, then grab one based on the column in question.
enum column { a, b, c}
Map<column, string> str;
static {
str.put(a, "select * from tbl where a = ? ");
...
}
then just grab one out of the map later based on the enum. String appends in sql statements have a way of becoming security problems in the future.
Use a dynamic query and a java.sql.Statement:
String whereClause = c + " = " + i;
// Form the dynamic Query
StringBuffer query = new StringBuffer( "SELECT * FROM TABLE" );
// Add WHERE clause if any
query.append(" WHERE " + whereClause);
// Create a SQL statement context to execute the Query
Statement stmt = con.createStatement();
// Execute the formed query and obtain the ResultSet
ResultSet resultSet = stmt.executeQuery(query.toString());
can't you do this:
String c;// the name of the column
...
String sql = "select * from table where " + c + " = ?";
pre = con.prepareStatement(sql);
pre.setString(1, i);
rs = pre.executeQuery();
?
If not then this might be a solution:
String c;// the name of the column
...
String sql = "select * from table where ('C1' = ? AND C1 = ?)
OR ('C2' = ? AND C2 = ?)
OR ('C3' = ? AND C3 = ?)"
pre = con.prepareStatement(sql);
pre.setString(1, c);
pre.setString(2, i);
pre.setString(3, c);
pre.setString(4, i);
pre.setString(5, c);
pre.setString(6, i);
rs = pre.executeQuery();