I have problem with SQL query in JAVA.
JAVA code:
public boolean zeKontrolaExistujiciZalohyTest(String datum) {
try {
connected();
boolean existujeZaloha = false;
int pocet;
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('"+datum+"', 'dd.mm.yyyy'), 'mm.yyyy')");
rs.next();
pocet = rs.getInt(1);
rs.close();
closed();
if (pocet >= 0) {
existujeZaloha = true;
} else {
existujeZaloha = false;
}
return existujeZaloha;
} catch (Exception e) {
e.printStackTrace();
Dialogs.create()
.title("Exception Dialog")
.showException(e);
return true;
}
}
SQL query in SQL Developer:
SELECT count(id) FROM pbtest.u_zalohy_energie
WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('15.09.2014', 'dd.mm.yyyy'), 'mm.yyyy');
When I run JAVA code, so result a variable is "pocet = 0". But, when I run SQL query in any the SQL Developer, so result column COUNT(id) is "1".
When I do change the SQL query, let me run JAVA code retuns a variable "pocet = 1".
Change sql code:
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE datum = TO_DATE('"+datum+"', 'dd.mm.yyyy')");
Does anyone know where is the problem?
For information: I use an Oracle database.
Thank you.
datum is string
SELECT count(id)
FROM pbtest.u_zalohy_energie
WHERE TO_DATE(datum, 'dd.mm.yyyy') = TO_DATE('15.09.2014', 'dd.mm.yyyy');
datum is date
SELECT count(id)
FROM pbtest.u_zalohy_energie
WHERE TRUNC(datum) = TO_DATE('15.09.2014', 'dd.mm.yyyy');
If datum is date, it might contain time component too. So remove it. using TRUNC()
TRUNC(datum) = TO_DATE('15.09.2014', 'dd.mm.yyyy');
Java code:
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE TRUNC(datum) = TO_DATE('"+datum+"', 'dd.mm.yyyy')");
As a side note, use PreparedStatement and bind variables to avoid SQL*Injection
Your statement has a syntax error
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('"+datum+"', 'dd.mm.yyyy'), 'mm.yyyy')");
the executed query would be
SELECT count(id) FROM pbtest.u_zalohy_energie\nWHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('15.09.2014'', 'dd.mm.yyyy'), 'mm.yyyy')")
You should remove the "\n" as this will not lead in a line break.
Try it as
ResultSet rs = statement.executeQuery("SELECT count(id) FROM " + table_ze
+ " WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('"+datum+"', 'dd.mm.yyyy'), 'mm.yyyy')");
Take also into consideration the comment from Maheswaran Ravisankar about: "... PreparedStatement and bind variables to avoid SQL*Injection"
Thank you for your advice, I solved the problem as follows:
public boolean zeKontrolaExistujiciZalohy(String datum, String typZalohy, String zalohaNaMesic) {
connected();
boolean existujeZaloha = false;
int pocet = 0;
ResultSet rs;
PreparedStatement pstmt = null;
try{
statement = connection.createStatement();
String SQL = "SELECT count(id) AS pocet FROM " + table_ze + " WHERE (EXTRACT(MONTH FROM datum)) = (EXTRACT(MONTH FROM to_date(?, 'dd.mm.yyyy'))) "
+ "AND (EXTRACT(YEAR FROM datum)) = (EXTRACT(YEAR FROM to_date(?, 'dd.mm.yyyy')))"
+ "AND typ_zalohy = ? "
+ "AND zaloha_na_mesic = ? ";
pstmt = connection.prepareStatement(SQL);
pstmt.setString(1, datum);
pstmt.setString(2, datum);
pstmt.setString(3, typZalohy);
pstmt.setString(4, zalohaNaMesic);
rs = pstmt.executeQuery();
while(rs.next()){
pocet = rs.getInt("pocet");
}
rs.close();
if (pocet > 0) {
existujeZaloha = true;
} else {
existujeZaloha = false;
}
return existujeZaloha;
}
catch(SQLException ex){
Dialogs.create()
.title("Exception Dialog")
.showException(ex);
return true;
}
}
Related
I updated my database from SQLite db to MySQL and I suddenly I get this error:
java.sql.SQLException: No operations allowed after statement closed.
public boolean isEnough(int quantity, String item) throws SQLException {
boolean enough = false;
PreparedStatement pst = null;
ResultSet rs = null;
String sql = "SELECT * FROM Stock WHERE Item_name='" + item + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
int temp = rs.getInt(3);
if (quantity > temp) {
stmt.close();
enough = false;
} else if (quantity <= temp) {
enough = true;
int updatedStock = temp - quantity;
String sql_1 = "UPDATE Stock SET Item_quantity ='" + updatedStock + "' WHERE Item_name ='" + item + "'";
stmt.executeUpdate(sql_1); //error here
String sql_2 = "SELECT * FROM Stock WHERE Item_name='" + item + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
System.out.println(rs);
if (rs.next()) {
int isZero = rs.getInt(3);
if (isZero == 0) {
String sql_3 = "DELETE FROM Stock WHERE Item_name = '" + item + "'";
stmt.executeUpdate(sql_3);
JOptionPane.showMessageDialog(this, "Order Added\nItem is now out of Stock and removed from Stock database automatically.");
}
}
}
}
stmt.close();
return enough;
}
I'm closing connection and statement after every update, but I have no idea how to fix this error. If I go back to SQLite db this error disappears. I'm new to MySQL, so pardon me if I'm doing something wrong.
im trying to update a column using jsp
here i want my count column value to be updated as zero
count = 0
how can i do that. through this code value is not updating
String code = request.getParameter("code");
Connection conn = null;
Statement st=null;
ResultSet rs = null;
PreparedStatement ps = null;
int count = 0;
try{
conn = DataBaseConnection.initializeDatabase();
String query1 = null;
conn.setAutoCommit(false);
query1 = "update employee set count = ? where code= ' +code+' ";
ps = conn.prepareStatement(query1);
ps.setInt(1, count);
ps.executeUpdate();
}
catch (Exception e) {
e.printStackTrace();
}
here is my record in db
employee table
CODE VARCHAR2(12)
COUNT NUMBER(3)
You can replace
"update employee set count = ? where code= ' +code+' ";
with
"update employee set count = ? where code= '" + code + "'";
e.g. if the value of code is xyz then after this change, the query will become:
"update employee set count = ? where code= 'xyz'";
However, I recommend you do it as follows to avoid the SQL Injection:
query1 = "update employee set count = ? where code= ?";
ps = conn.prepareStatement(query1);
ps.setInt(1, count);
ps.setString(2, code);
I am using JDBC and mySQL to do an application for a family. After logging in into the system, the user can register for a family account. By SQL statement, I want to ensure that the input they keyed in is not repeated and they can only register when the database have a NRIC of them individually. I am working with JDBC and implementing the SQL statement in Java also. For now my problem is the system does not validate the input the user keys in and let's the information to be passed to database easily. Would appreciate some help!
*NRIC = Identity Card No
Snapshots of Database:
User Database
Family Account Database
Code
public boolean regFamily(FamilyAccount myFam, Customer myCust) throws Exception {
int fid = 0;
try {
String selectStatement2 = "SELECT * from familyok.user where nric = ? and familyid is NOT NULL ";
PreparedStatement pStmt2 = con.prepareStatement(selectStatement2);
pStmt2.setString(1, myCust.getNric());
ResultSet rs2 = pStmt2.executeQuery();
if (rs2.next()) {
String insertStatement = "Insert into familyok.familyaccount (familyname, fnric1, fnric2, fnric3)";
insertStatement = insertStatement + "values (?,?,?,?)";
PreparedStatement prepStmt = con.prepareStatement(insertStatement);
prepStmt.setString(1, myFam.getFamilyname());
prepStmt.setString(2, myFam.getFnric1());
prepStmt.setString(3, myFam.getFnric2());
prepStmt.setString(4, myFam.getFnric3());
int status = prepStmt.executeUpdate();
if (status != 0) {
String selectStatement = "SELECT fid FROM familyok.familyaccount WHERE fnric1=?";
PreparedStatement pStmt = con.prepareStatement(selectStatement);
pStmt.setString(1, myFam.getFnric1());
ResultSet rs = pStmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt("fid") + "\t");
fid = rs.getInt("fid");
String updateStatement = "update familyok.user set familyid=?, familyname1=? where nric in (?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(updateStatement);
preparedStmt.setInt(1, fid);
preparedStmt.setString(2, myFam.getFamilyname());
preparedStmt.setString(3, myFam.getFnric1());
preparedStmt.setString(4, myFam.getFnric2());
preparedStmt.setString(5, myFam.getFnric3());
int status2 = preparedStmt.executeUpdate();
System.out.println("update=" + preparedStmt.toString());
if (status2 != 0) {
System.out.println("Family Account Created");
return true;
}
}
}
}
else
{
System.out.println("Can't Register");
return false;
}
} catch (Exception ex) {
throw new Exception("Error: " + ex.getMessage());
}
return false;
}
On this java method I am trying to get data from a ms-sql server. I am trying to get the int value from a column , Now the columns I am using are all int's but for some reason when i try pulling it as a INT I am getting a number format error saying that the column is a nvarchar. Not sure what is happening and when i ran the System.out I am noticing I am only pulling the column name but no data that the column has. Here is my method, I am not sure what I am doing wrong or what is missing from this. Any help will be greatly appreciated thank you.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
String type = getTypeOfTimeOff().replaceAll("\\s+","");
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = "SELECT ? FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getTypeOfTimeOff().replaceAll("\\s+",""));
preparedStatement.setString(2, getEmpName());
preparedStatement.setString(3, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
//int checker = rs.getInt(1);
String acheck = rs.getString(1);
System.out.println("TIME off the user has : " + acheck);
int checker = Integer.valueOf(acheck);
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int aCheck = rs.getInt("column name");
}
}catch(){}
like this
For some reason what i did was add an AS to my query along with adding a if statement to my code caused the resultset to work with my code and allowed me to pull numbers from my database. Thank you for your help. Here is the updated code i added if it helps anyone.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = null;
if(getTypeOfTimeOff().equalsIgnoreCase("Vacation Day"))
selectProject = "SELECT VacationDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Bonus Day"))
selectProject = "SELECT BonusDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Birthday Day"))
selectProject = "SELECT BirthdayDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
System.out.println("Query String : " + selectProject);
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getEmpName());
preparedStatement.setString(2, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
int checker = 0 ;
checker = rs.getInt("dayList");
System.out.println("Days the user has off are: " + checker );
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}
I get an error in this function but I don't know why.
Can you help me?
The error is in the row where I call executeQuery()
public static int numeroElementi(String table) throws SQLException {
// viene reistanziata perché questa è una funziona statica!
String DB_URL = "jdbc:mysql://localhost:3306/kmzero";
Connection connection = DriverManager.getConnection(DB_URL, "root", "root");
String query = "SELECT COUNT(*) AS count FROM ? ";
PreparedStatement pStatement = connection.prepareStatement(query);
pStatement.setString(1, table);
try {
ResultSet resultSet = pStatement.executeQuery();
try {
if (resultSet.next())
return resultSet.getInt("count");
else
return 0;
} finally {
resultSet.close();
}
} finally {
pStatement.close();
}
}
I think you cannot pass the tablename (also columnNames) as a parameter and this is the time when tableName should be concatenated in your string.
String query = "SELECT COUNT(*) AS count FROM " + table;
if your table needs to be escape,
String query = "SELECT COUNT(*) AS count FROM `" + table + "`";