Error in sql query to fetch data from wamp server [duplicate] - java

I had tried several times using prepared statements but it returns SQL exception. here is my code:
public ArrayList<String> name(String mobile, String password) {
ArrayList<String> getdata = new ArrayList<String>();
PreparedStatement stmt = null;
try {
String login = "select mobile, password from tbl_1 join tbl_2 on tbl_1.fk_id=2.Pk_ID where mobile=? and password=?";
String data = "select * from tbl_2 where password='" + password + "'";
PreparedStatement preparedStatement = conn.prepareStatement(login);
preparedStatement.setString(1, mobile);
preparedStatement.setString(1, password);
ResultSet rs = preparedStatement.executeQuery(login);
Statement stmts = (Statement) conn.createStatement();
if (rs.next()) {
System.out.println("Db inside RS");
ResultSet data = stmts.executeQuery(data);
while (data.next()) { /* looping through the resultset */
getdata.add(data.getString("name"));
getdata.add(data.getString("place"));
getdata.add(data.getString("age"));
getdata.add(data.getString("job"));
}
}
} catch (Exception e) {
System.out.println(e);
}
return getdata;
}
While running this, I got the following SQL exception:
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 '? and password=?' at line 1.
Any suggestion to make this work?
any piece of code is appreciated.

You need to use:
preparedStatement.executeQuery();
instead of
preparedStatement.executeQuery(login);
when you pass in a string to executeQuery() that query is executed literally and thus the ? is send to the database which then creates the error. By passing query string you are not execution the "cached" prepared statement for which you passed the values.

For both parameter you use preparedStatement.setString(1, ..); so the first parameter is set two times. but you never set the value for second parameter.
so change
preparedStatement.setString(1, mobile);
preparedStatement.setString(1, password);
to
preparedStatement.setString(1, mobile);
preparedStatement.setString(2, password);

Related

Insert query not executing

I want to insert the product the user selected into a table called cart which has two columns: cart_id and item_id_FK both are foreign keys. User_id and id are passed in the constructor and then inserted into cart_id and item_id_fk.
No errors are showing in the code, I double checked the connection username and password, everything works fine except for the cart table.
I tried putting a try and catch statement inside and repeating the steps it didn't work.
if (e.getSource()==AddToCartBtn)
{
//Check to see if item is available
String SizeSelection;
SizeSelection = SizeCmbx.getSelectedItem().toString();
String DBURL ="JDBC:MySql://localhost:3306/shoponline?useSSL=true";
String USER ="root";
String PASSWORD ="12345678";
try {
Connection con = DriverManager.getConnection(DBURL, USER, PASSWORD);
String sql2 = String.format("select itemid,size,productid_fk from items where size='%s' and productid_fk=%d",SizeSelection,id);
PreparedStatement statement = con.prepareStatement(sql2);
ResultSet result = statement.executeQuery(sql2);
String sql3 = "insert into cart (CartID, ItemID_FK)" + " values (?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(sql3);
preparedStmt.setInt(1, user_ID);
preparedStmt.setInt(2, id);
if(result.next())
{
//if item is available
// execute the preparedstatement
preparedStmt.execute();
}//end if
con.close();
}// end try
catch (SQLException ex){
ex.printStackTrace();
}//end catch
Change executeQuery to executeUpdate:
executeQuery(sql3)
to
executeUpdate(sql3)
I believe integers don't need the ' ' around them to be inserted, you may try removing those as well. It may be mistaking them as characters or something similiar.
Otherwise if neither of those above fixes work, try something like this:
String query = "insert into cart (CartID, ItemID_FK)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, xInt);
preparedStmt.setInt(2, yInt);
// execute the preparedstatement
preparedStmt.execute();
conn.close();

Return id after sql insert java [duplicate]

Is there a way to retrieve the auto generated key from a DB query when using a java query with prepared statements.
For example, I know AutoGeneratedKeys can work as follows.
stmt = conn.createStatement();
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
However. What if I want to do an insert with a prepared Statement.
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql);
//this is an error
stmt.executeUpdate(Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
//this is an error since the above is an error
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
Is there a way to do this that I don't know about. It seems from the javadoc that PreparedStatements can't return the Auto Generated ID.
Yes. See here. Section 7.1.9. Change your code to:
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.executeUpdate();
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
There's a couple of ways, and it seems different jdbc drivers handles things a bit different, or not at all in some cases(some will only give you autogenerated primary keys, not other columns) but the basic forms are
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Or use this form:
String autogenColumns[] = {"column1","column2"};
stmt = conn.prepareStatement(sql, autogenColumns)
Yes, There is a way. I just found this hiding in the java doc.
They way is to pass the AutoGeneratedKeys id as follows
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
I'm one of those that surfed through a few threads looking for solution of this issue ... and finally get it to work. FOR THOSE USING jdbc:oracle:thin: with ojdbc6.jar PLEASE TAKE NOTE:
You can use either methods:
(Method 1)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
myPrepStatement = <Connection>.prepareStatement(yourSQL, Statement.RETURN_GENERATED_KEYS);
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
java.sql.RowId rid=rs.getRowId(1);
//what you get is only a RowId ref, try make use of it anyway U could think of
System.out.println(rid);
}
} catch (SQLException e) {
//
}
(Method 2)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
//IMPORTANT: here's where other threads don tell U, you need to list ALL cols
//mentioned in your query in the array
myPrepStatement = <Connection>.prepareStatement(yourSQL, new String[]{"Id","Col2","Col3"});
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
//In this exp, the autoKey val is in 1st col
int id=rs.getLong(1);
//now this's a real value of col Id
System.out.println(id);
}
} catch (SQLException e) {
//
}
Basically, try not used Method1 if you just want the value of SEQ.Nextval, b'cse it just return the RowID ref that you may cracked your head finding way to make use of it, which also don fit all data type you tried casting it to! This may works fine (return actual val) in MySQL, DB2 but not in Oracle.
AND, turn off your SQL Developer, Toad or any client which use the same login session to do INSERT when you're debugging. It MAY not affect you every time (debugging call) ... until you find your apps freeze without exception for some time. Yes ... halt without exception!
Connection connection=null;
int generatedkey=0;
PreparedStatement pstmt=connection.prepareStatement("Your insert query");
ResultSet rs=pstmt.getGeneratedKeys();
if (rs.next()) {
generatedkey=rs.getInt(1);
System.out.println("Auto Generated Primary Key " + generatedkey);
}

Query cannot be executed if parameter value is incorrect

I have a query which works fine in local database. I just moved into a remote database and the error occurred as follow:
DAO:
public String changeLecture(String CoursesID, String strDate, String strTime, String endTime, String venue, NewCourseInfoBean courseInfo) {
//preparing some objects for connection
Connection currentCon = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
String result = "";
try
{
//connect to DB
currentCon = ConnectionManager.getConnection();
pstmt = currentCon.prepareStatement("select * from course_info where course_code=? and c_date=? and start_time=? and end_time=? and venue=?", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
pstmt.setString(1, CoursesID);
pstmt.setString(2, strDate);
pstmt.setString(3, strTime);
pstmt.setString(4, endTime);
pstmt.setString(5, venue);
pstmt.executeQuery();
rs = pstmt.getResultSet();
//check whether the class is existed
if (rs.next())
{
rs.updateObject("c_date", courseInfo.getChangeC_date());
rs.updateObject("start_time", courseInfo.getChangeStart_time());
rs.updateObject("end_time", courseInfo.getChangeEnd_time());
rs.updateObject("venue", courseInfo.getChangeVenue());
rs.updateRow();
result = "Lecture slot updated successfully!";
}else{
result = "You do not have lecture with the details provided in 'current lecture slot' fields. Please check your schedule.";
}
}
//catch
//some exception handling
return result;
}
error message:
[MySQL][ODBC 5.3(a) Driver]
[mysqld-5.5.43-0ubuntu0.14.04.1]
Table 'sql679933.COURSE_INFO' doesn't exist
Whenever I provide a right dataset, the data in table course_info will be updated. However, the programs stops at line pstmt.executeQuery(); if wrong dataset is provided.
Eg.
correct data: select * from course_info where course_code='SSK3100'..... (works fine)
incorrect data: select * from course_info where course_code='SSK333'......(cannot execute query)
This query works fine in local db, so what's goes wrong here? :( Please help.

quotation marks in string parameter insert statement

Hi I've been trying to insert a string into a sqlite database through java. but the string parameter I'm passing in the values sql statement has quotation marks in it as content. I'm thinking that is the error I'm getting why it isn't inserting into the database. is there a way to bypass the quotation marks in the insert statement. thank you.
this is the code:
public void addNote(String topicadd, String contentadd) throws Exception
{
try
{
getConnection();
statement = conn.createStatement();
statement.executeUpdate("insert into tbl_notes (notes_topic, notes_content) values ('" + topicadd + "', '" + contentadd +"')");
System.out.println("inserted note");
}
catch (Exception m)
{`enter code here`
System.out.println("error insert topic");
System.out.println(m.getMessage());
}
}
this is the parameter kind of long... this is all in contentadd
import java.sql.*;
Resultset rset = null; (this has no new ResultSet() initialization)
Connection conn = null; (this has no new initialization too...)
Statement statement = null; (this has now new initialization)
always.....
try
{
}
catch (Exception e) <- can switch e for any other alphabet
{
e.getMessage();
System.out.println("error this module"); <- personal practice
throw e;
}
- getting connection
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:m.db");
*** this is sqlite connection format 'm.db' is the database name
establish connection first..
statement syntax follows:
statement = conn.createStatement();
rset = statement.executeQuery("select * from tbl_notes");
- executeQuery is used for SELECT sql statements
rset = statement.executeUpdate("insert into tbl_notes (ID, status) values
('100', 'status here');
the whole text is in string contentadd, I'm making a short note-taking program... Well, it doesn't execute the insert statement... error somewhere near (word from text) on command prompt... I'm using sqlite... Please let me know if you need more detail. thank you again.
Use a PreparedStatement to insert values containing special characters:
getConnection();
PreparedStatement statement = conn.prepareStatement("insert into tbl_notes (notes_topic, notes_content) values (?, ?)");
statement.setString(1, topicadd);
statement.setString(2, contentadd);
statement.executeUpdate();
As you see you can use parameters with a PreparedStatement which can contain also quotation marks.
Also you get some protection against SQL injection because the Strings given to a PreparedStatement are escaped accordingly.

Adding to table using Jdbc & ms managment system

I bumped into this problem and i cannot figure out what is wrong with this code. I use jdbc and ms managment system for the databse and its connection.
code:
try {
//create user
preparedStatement = conn.prepareStatement("INSERT INTO Users(name, pass, type) VALUES (nick=?,pass=?,type=?)",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
preparedStatement.setString(1, user.getNickName());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setInt(3, type);
rs = preparedStatement.executeQuery();
System.out.println(rs.toString());
catch (Exception e) {
System.out.println("Exception: " + e);
}
error:
Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '='.
The way you are using the ? characters is invalid in JDBC:
"INSERT INTO Users(name, pass, type) VALUES (nick=?,pass=?,type=?)
One ? represents the whole bind variable. Try
"INSERT INTO Users(name, pass, type) VALUES (?, ?, ?)"
Also, use executeUpdate to execute an insert statement (or update, or delete).
Remove the field names from the value list. These are already in the name list. Also use executeUpdate for database write operations:
preparedStatement =
conn.prepareStatement("INSERT INTO Users(name, pass, type) VALUES (?,?,?)",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
preparedStatement.setString(1, user.getNickName());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setInt(3, type);
int rowCount = preparedStatement.executeUpdate();

Categories

Resources