MySQL LIMIT with OFFSET not working as expected - mysql

PreparedStatement ps is working as expected with user_type being updated for the first row however, my second statement (ps1) which should update the second row isn't. As the only change is the offset 'LIMIT 1, 1;' I can only assume that's why the system throws a MYSQLSyntaxErrorException. I'm new to MySQL so unsure why it's throwing an exception and how to achieve the same by trying something else.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/child_timer", "root", "");
PreparedStatement ps = conn.prepareStatement("UPDATE user_profile SET user_type=? ORDER BY user_id ASC LIMIT 1;");
ps.setString(1, sp.getUserType().name());
int x = ps.executeUpdate();
if (x > 0) {
alertDialogBuilder(AlertType.INFORMATION, "Success", null, "Changes have been successfully saved.");
}
PreparedStatement ps1 = conn.prepareStatement("UPDATE user_profile SET user_type=? ORDER BY user_id ASC LIMIT 1, 1;");
ps1.setString(1, sp.getUserType1().name());
int x1 = ps1.executeUpdate();
if (x1 > 0) {
alertDialogBuilder(AlertType.INFORMATION, "Success", null, "Changes have been successfully saved.");
} catch (Exception e1) {
System.out.println(e1);
}

Theres no offset in a MySQL Update LIMIT statement.
Provide a minimum id to create an offset instead like so:
wHERE user_id >= :offset

Related

Error catching mysql statement in java

Hello so i'm trying to code my own type of error catching on a sql statement. On my method add order i want to add some way of stopping someone from selling a product which has no stock. My code below does not yet do that. I can add orders and update the stock amount but i haven't figured out a way of adding an if statement that works.
#FXML
public void AddOrder(ActionEvent event) {
String orderID = orderBox.getText();
String customerID = customerBox.getText();
String productID = productBox.getText();
String amount = amountBox.getText();
// String cost = costBox.getText();
String date = dateBox.getText();
PreparedStatement sample;
dc = new Database();
try {
c = dc.Connect();
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
ResultSet rs = sample.executeQuery();
while (rs.next()) {
Integer amount2 = rs.getInt("Amount");
if (amount2 <= 0) {
System.out.println("No stock exists");
} else {
query = c.prepareStatement(
"INSERT INTO ordertable (orderID,customerID,productID,Amount,Date)VALUES(?,?,?,?,?)");
update = c.prepareStatement("UPDATE inventory set stockAmount = stockAmount-? WHERE productID =?");
update.setString(1, amount);
update.setString(2, productID);
update.execute();
query.setString(1, orderID);
query.setString(2, customerID);
query.setString(3, productID);
query.setString(4, amount);
// query.setString(5, cost);
query.setString(5, date);
query.executeUpdate();
// update.executeUpdate();
Alert confirmation = new Alert(Alert.AlertType.CONFIRMATION, "Saved");
// closeConfirmation.showMessageDialog(this, "Saved");
confirmation.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
orderBox.clear();
customerBox.clear();
productBox.clear();
amountBox.clear();
dateBox.clear();
loadDataFromDatabase(event);
}
Below is the error i'm getting
java.sql.SQLException: No value specified for parameter 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at
If you are just having trouble because of that exception, check these lines:
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
ResultSet rs = sample.executeQuery();
The query is defined to accept a parameter for productID, but you haven't given it a value prior to executing the statement. You'll need to change the query so that it doesn't require a parameter or assign a value to the parameter, like this:
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
sample.setString(1, productID);
ResultSet rs = sample.executeQuery();

How to write query for count of a column in jdbc

I have a table attendance in which columns are id,name,date,status.Here what's the my problem is,If i select two dates(start date and end date) in my html page,I want to generate a attendance report of a student between the range of dates with name also no of present days also.How to write query for selecting name of the student and count of present days of particular student.For all help thanks in advance.
i wrote query like below.
String sql = "select student_name,count(status) from attendance where attendance.date>=? and attendance.date<=? and attendance.status=?";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test_schema", "root", "root");
String sql = "select student_name from attendance where attendance.date>=? and attendance.date<=? and attendance.status=?";
PreparedStatement pstmt = con.prepareStatement(sql);
//pstmt.setString(1, "Present");
pstmt.setString(1, stDate);
pstmt.setString(2, enDate);
pstmt.setString(3, "Present");
rs = pstmt.executeQuery();
while (rs.next()) {
java.sql.ResultSetMetaData rsmd=rs.getMetaData();
int colCount = rsmd.getColumnCount();
System.out.println("colCount :" + colCount);
System.out.println("count>>"+colCount);
StudentMark ge = new StudentMark();
ge.setStudentName(rs.getString(1));
stList.add(ge);
}
out.print(stList);
out.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
You can use the ResultSetMetaData to get the column count for any select query's result.
ResultSet rs= ... //Statement's result.
ResultSetMetaData rsmd= rs.getMetaData();
int colCount = rsmd.getColumnCount();

retrieving every attribute of every column from every row of a table mysql java

So far I know that it's possible to select the nth row from a table using the following code SELECT * FROM table ORDER BY column_name LIMIT n-1,1 ; In the following code I am trying to retrieve every attribute of every column from every row of a table named responsable which has the following columns :id,name,surname,mail,password. id is an integer while the other columns' type is string
java.sql.Connection connection = null;
int rowCount;
try {connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","root","");
Statement stmt = null;
ResultSet result = null;
ResultSet rs = null;
rs = stmt.executeQuery("SELECT COUNT(*) FROM responsable");
rowCount = rs.getInt(1);
if(rowCount!=0)
{
for(int i=0;i<rowCount;i++)
{result= stmt.executeQuery("SELECT * FROM responsable ORDER BY id LIMIT"+i+",1");
System.out.put(result.getInt(1));
System.out.put(result.getString(2));
System.out.put(result.getString(3));
System.out.put(result.getString(4));
System.out.put(result.getString(5));}
}
}catch (Exception ex) {
out.println("Unable to connect to database");
}
I am trying to execute this code but I am getting no result.
Any help would be appreciated.
Your stmt variable is null. You need to create the statement first.
Statement stmt = connection.createStatement();
Also, you need to call next() to retrieve the next row from your resultset.
E.g.
if (rs.next()) {
rowCount = rs.getInt(1);
}
....
if (result.next()) {
System.out.put(result.getInt(1));
System.out.put(result.getString(2));
System.out.put(result.getString(3));
System.out.put(result.getString(4));
System.out.put(result.getString(5));
}

timestamp issue in mysql

While executing the following query in querybrowser i;m getting correct date.But in jdbc code resultset is returning incorrect date.
pstmt = con.prepareStatement("select DATE(sih.loaded_date) from tab_ats_sellthroughloader_history sih order by loaded_date desc limit 1");
rs = pstmt.executeQuery();
java.sql.Timestamp saveDate = null;
while (rs.next()) {
saveDate = rs.getTimestamp(1);
}
System.out.println("result:::::::::::::::::"+saveDate);

mysql prepared statement : Update query

I am trying to execute a C program, using mysql C API, connecting to mysql with an update query and I am not getting any compilation or linking errors , but rows are not getting updated in the db table.
When I run this code I am getting empty values updated in emp. status field
#define STRING_SIZE 256
char* eStatus,myeStatus;
int myempid,empid;
int i;
for(i = 0; i < 5 ; i++){
const char* sqlQuery = "update employee_info set estatus = ? where empID = ?";
if (mysql_stmt_prepare(stmt, sqlQuery, strlen(sqlQuery))) {
fprintf(stderr, " mysql_stmt_prepare(), update failed\n");
fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
return -1;
}
memset(param, 0, sizeof(param)); /* zero the structures */
if (info.state == 2)
eStatus = "present";
else
eStatus = "absent";
empid = i;
// Init param structure
// Select
param[0].buffer_type = MYSQL_TYPE_STRING;
param[0].buffer = (void *) &eStatus;
param[0].buffer_length = STRING_SIZE;
param[0].is_null = 0;
param[0].length = &str_length;
param[1].buffer_type = MYSQL_TYPE_SHORT;
param[1].buffer = (void *) &myempID;
param[1].buffer_length = STRING_SIZE;
param[1].is_null = 0;
param[1].length = 0;
myeStatus = eStatus;
myempid = empid;
if (mysql_stmt_bind_param(stmt, param) != 0) {
fprintf(stderr, " mysql_stmt_bind_param() failed\n");
fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
return -1;
}
/* Execute the statement */
if (mysql_stmt_execute(stmt)) {
fprintf(stderr, " mysql_stmt_execute(), failed\n");
fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
return -1;
}
} // end of for loop
Table schema in mysql
empid INT(11)
estatus varchar(10)
I am not able to figure out why status is not getting updated in mysql table. Is it a mismatch of datatypes, or values are not binded properly to sqlquery?
Any clue? Thanks.
You can find here : Writing into mysql database from a single board computer using c a complete example on how to use MYSQL C API to perform queries, if you still have some trouble, please post the whole code.
Why are you trying to use "where empID = ?". If you want it to run for every employee simply omit the where clause. If it is for a specific employee, then his id should be there.
There might be more issues, but this was the first one i found.
You might verify by trying to execute the same query on mysql command line prompt.
Edit: I also don't see any database connection being established and any info related to that. Some thing like
MYSQL *conn = mysql_init(NULL);
*conn = mysql_real_connect(*conn, DB_HOST, DB_USER, DB_PASS, DB_NAME, 0, NULL, flags);
if (*conn != NULL)
{
printf("Connection Successfull\n");
status = 0;
}