MySQLSyntaxErrorException in JAVA - java

Somebody please help me.I am doing things right but i am getting an error.It is a JAVA application linked to MYSQL wamp server.
ERROR:
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 'Chege' at line 1
MY CODE:
public class MyQuery {
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://"
+ "localhost:3306/employee_certificate", "root", "");
} catch (SQLException ex) {
Logger.getLogger(Query.class.getName())
.log(Level.SEVERE, null, ex);
}
return con;
}
public ArrayList<Item> getData(String EmpName) {
ArrayList<Item> list = new ArrayList<Item>();
Connection con = getConnection();
Statement st;
ResultSet rs;
try {
st = con.createStatement();
rs = st.executeQuery("SELECT Emp_Id, Emp_Name, Department "
+ "FROM staff WHERE Emp_Name = " + EmpName + " ");
Item I;
while (rs.next()) {
I = new Item(
rs.getString("Emp_Id"),
rs.getString("Emp_Name"),
rs.getString("Department"));
list.add(I);
}
} catch (SQLException ex) {
Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
}

Your query string is not correct. Should be something like the following:
rs=st.executeQuery("SELECT Emp_Id, Emp_Name, Department "
+ "FROM staff WHERE Emp_Name = '"+EmpName+"'");
But I'd recommend to use a PreparedStatement object for sending SQL statements to the database.
String query = "SELECT Emp_Id, Emp_Name, Department FROM staff WHERE Emp_Name = ?";
PreparedStatement preStatement = conn.prepareStatement(query);
preStatement.setString(1, EmpName);
ResultSet result = preStatement.executeQuery();
This approach is safer and more convenient.

You have a little problem in your query:
try {
st = con.createStatement();
//Add quotes 'YourString'
rs = st.executeQuery("SELECT Emp_Id, Emp_Name, Department "
+ "FROM staff WHERE Emp_Name = '" + EmpName + "' ");
Item I;
while (rs.next()) {
I = new Item(rs.getString("Emp_Id"), rs.getString("Emp_Name"), rs.getString("Department"));
list.add(I);
}
} catch (SQLException ex) {
Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex);
}
or for a safety Query use prepared statement:
try {
PreparedStatement ps = connection.prepareStatement("SELECT Emp_Id, Emp_Name, Department FROM staff WHERE Emp_Name = ?");
ps.setString(1, EmpName);
rs = ps.executeUpdate();
Item I;
while (rs.next()) {
I = new Item(rs.getString("Emp_Id"), rs.getString("Emp_Name"), rs.getString("Department"));
list.add(I);
}
} catch (SQLException ex) {
Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex);
}

Related

com.microsoft.sqlserver.jdbc.SQLServerException: The value is not set for the parameter number 1

I have a problem with line pstmt.setLong(1, id);. I get an error that the value is not set for the parameter number 1. If I use the String SQL without the question mark, it works. Also, when I use ARM the PreparedStatement and ResultSet are not automatically closed so I have to close them, and finally doesn't seem to work either
#Override
public Company getCompany(long id) {
Connection con = ConnectionPool.getInstance().getConnection();
String sql = "SELECT * FROM Company WHERE ID=?";
//String sql = "SELECT * FROM Company WHERE ID=" + id;
Company company = new Company();
try (
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();)
{
pstmt.setLong(1, id);
if (rs.next()) {
company.setId(rs.getLong(1));
company.setCompName(rs.getString(2));
company.setPassword(rs.getString(3));
company.setEmail(rs.getString(4));
} else {
System.out.println("Company with ID: " + id + " could not be found\n");
}
pstmt.close();
rs.close();
} catch (SQLException e) {
CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);
System.out.println(ex.getMessage());
System.out.println(e);
}
ConnectionPool.getInstance().returnConnection(con);
return company;
}
Set the parameter before executing the query.
Also, You don't need to close Statement and result sets defined in try-with-resource statements as they'll be closed automatically when you leave the try scope.
try(PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setLong(1, id);
try(ResultSet rs = pstmt.executeQuery()) {
// do stuff
}
}
You need to set the PreparedStatement's parameters before executing it. Also note that this you're using the try-with-resource syntax you shouldn't close the resources yourself:
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setLong(1, id);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
company.setId(rs.getLong(1));
company.setCompName(rs.getString(2));
company.setPassword(rs.getString(3));
company.setEmail(rs.getString(4));
} else {
System.out.println("Company with ID: " + id + " could not be found\n");
}
}
} catch (SQLException e) {
CouponSystemException ex = new CouponSystemException("Company with ID: " + id + " could not be retrieved\n", e);
System.out.println(ex.getMessage());
System.out.println(e);
}

How to validate data using sql statement to ensure user does not breach the system

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

How do I return the contents of a ResultSet as a map?

I would like to know how I can return a result set from a query as a map.
This is my query where 'nameCodesString' is a list of strings e.g. ('raul', 'peter', 'shawn'):
try (PreparedStatement stmt = conn.prepareStatement("select n.CODE, l.VALUE"
+ " from TNAME n join TPROPERTIES l on n.UIDPK = l.OBJECT_UID"
+ " where n.CODE IN (" + nameCodesString + ")")) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
log.info("rs {}",rs);
nameCode = rs.getString(1);
displayName = rs.getString(2);
Person.add(new PersonDTO(nameCode, displayName, ""));
}
}
}
The result should be a code and a value. I am not sure how I can do this all in one connection to the database.
Hello that is my suggestion
String req="select n.CODE, l.VALUE from TNAME n join"
+" TPROPERTIES l on n.UIDPK = l.OBJECT_UID "
+" where n.CODE IN ?";
PreparedStatement stmt=null;
ResultSet rs=null;
try{
stmt=conn.prepareStatement(req);
stmt.setString(1, nameCodesString);
rs=stmt.executeQuery();
while(rs.next()){
nameCode = rs.getString(1);
displayName = rs.getString(2);
Person.add(new PersonDTO(nameCode, displayName, ""));
}
}
catch(SQLException ex){
System.out.println(ex);
}
finally{
if(rs!=null){
try{
rs.close();
}
catch(SQLException ex){}
}
if(stmt!=null){
try{
stmt.close();
}
catch(SQLException ex){}
}
if(conn!=null){
try{
conn.close();
}
catch(SQLException ex){}
}
}
It is just my suggestion i hope it can be a tip for you!
Best regards...
I failed to understand how preparedStatements should be used. In the end I decided not to use them and stick to executing a query string:
Map<String, String> personDetails = new Hashmap();
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select n.CODE, l.VALUE"
+ " from TNAME n join TPROPERTIES l on n.UIDPK = l.OBJECT_UID"
+ " where n.CODE IN (" + nameCodesString + ")")) {
while (rs.next()) {
nameCode = rs.getString(1);
displayName = rs.getString(2);
personDetails.put(nameCode, displayName);
}
}

Java sql Data pulling in the columnName but not the data

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

Can we use two queries using prepared statement in one method

Can we use two queries in one method while using prepared statement, I have tried using this but invalid column name exception is coming.
My code snippets is as follows.
public double getPayroll(){
ResultSet rs = null;
ResultSet rs2 = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getDBConnection();
int employeeId;
String q1 = "select e_salary,e_house_rent,e_conv_allow,e_id
from employee";
pstmt = conn.prepareStatement(q1);
rs = pstmt.executeQuery();
double dailyPay=0,basicPay=0,payroll2=0;
int houseRent=0,convAllow=0;
while (rs.next()) {
dailyPay = rs.getInt(1)*.03;
houseRent=rs.getInt(2);
convAllow=rs.getInt(3);
employeeId=rs.getInt(4);
}
String q2="select att_status from attendance where
e_id=employeeId";
pstmt = conn.prepareStatement(q2);
rs2 = pstmt.executeQuery();
int noOfPresents = 0;
while(rs2.next()){
noOfPresents+=1;
}
basicPay=dailyPay*noOfPresents;
payroll2+=basicPay+houseRent+convAllow;
return payroll2;
} catch (Exception e) {
e.printStackTrace();
return 0.0;
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Your problem is that the sql in q2 assumes that there is a column named employeeId, but I suspect you want to insert the value of the variable employeeId.
Change it to
select att_status from attendance where e_id=?
Then execute
pstmt.setString(1, employeeId);
before executing pstmt.executeQuery();

Categories

Resources