Query cannot be executed if parameter value is incorrect - java

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.

Related

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

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);

Copy table from one system to a h2 in memory DB through while loop not working

I'm trying to pull data from an onsite location into an in-memory h2 database, the below code pulls from the 'MLB.' table and results can be printed, however this then seems to skip the while loop and prints the 'completed' line. My connections definitely work, I've performed tests on the below code and I can write and select from the h2 table, as well as the db2 table outside of the loop.
Guidance on how to make the below work, pulling data from the MLB.SC_EP table into the in memory h2 table will be greatly appreciated.
public static void queryh2() throws SQLException {
Connection connection2 = getDBConnection();
Connection connection1 = getDZConnection();
Statement st1 = connection1.createStatement();
Statement createstmt = null;
PreparedStatement ps1 = null;
createstmt = connection2.createStatement();
createstmt.execute("CREATE TABLE testtable(CLIENTCOUNTRY varchar(255), CLIENTNAME varchar(255))");
st1.setFetchSize(10000);
ResultSet rs = st1.executeQuery("Select CLIENTCOUNTRY, CLIENTNAME from MLB.SC_EP");
while(rs.next())
{
// int res;
final String COUNTRY = rs.getString("CLIENTCOUNTRY");
final String OPPDESC = rs.getString("CLIENTNAME");
PreparedStatement ps = null;
ps = connection2.prepareStatement("insert into testtable values(?,?)");
ps.setString(1, COUNTRY);
ps.setString(2, OPPDESC);
ps.setFetchSize(10000);
ps.executeUpdate();
ResultSet rs1 = createstmt.executeQuery("select * from testtable");
System.out.println(rs1.getInt("CLIENTCOUNTRY"));
}
System.out.println("completed");
}

JAVA GUI - GET and SHOW DATA FROM MYSQL

I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.

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

How to fix my Prepared Statement to give me data from the DB in my application?

I have my Java program and I need to get data from my MYSQL DB,
I wrote this one out but its just sysout so getting data from my class and not using the Prepared Statement (I can delete the first 3 lines and it will work the same )
Could use some help to figure out how to get data from my DB and print it out
public void viewClientDetails(ClientsBean client) {
try {
PreparedStatement ps = connect.getConnection().prepareStatement(
"SELECT * FROM mbank.clients WHERE client_id = ?");
ps.setLong(1, client.getClient_id());
System.out.println(client.getClient_id());
System.out.println(client.getName());
System.out.println(client.getType());
System.out.println(client.getPhone());
System.out.println(client.getAddress());
System.out.println(client.getEmail());
System.out.println(client.getComment());
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"Problem occurs while trying to see client details");
}
}
Well you're not actually executing the prepared statement... you're just preparing it. You should call PreparedStatement.executeQuery and use the ResultSet it returns:
// ...code as before...
try (ResultSet results = ps.executeQuery()) {
while (results.next()) {
// Use results.getInt etc
}
}
(You should use a try-with-resources statement to close the PreparedStatement too - or a manual try/finally block if you're not using Java 7.)
You need to do executeQuery on the preparedstatement to get a result set back of the query you performed.
You are simply not executing the query. Add a PreparedStatement.executeQuery() call. And fetch the results from the returned ResultSet.
For example:
PreparedStatement ps = connect.getConnection().prepareStatement("SELECT * FROM mbank.clients WHERE client_id = ?");
ps.setLong(1, client.getClient_id());
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String userid = rs.getString("id");
String username = rs.getString("name");
}
As #Jon Skeet pointed out, the declaration of ResultSet in Java 7 is updated to:
public interface ResultSet extends Wrapper, AutoCloseable
It is AutoClosable now, which means that you can and should use the try-with-resource pattern.
You can do the below.
PreparedStatement ps = connect.getConnection().prepareStatement(
"SELECT * FROM mbank.clients WHERE client_id = ?");
resultSet = ps.executeQuery();
while (resultSet.next()) {
String user = resultSet.getString("<COLUMN_1>");
String website = resultSet.getString("<COLUMN_2>");
String summary = resultSet.getString("<COLUMN_3>");
}

Categories

Resources