Problem with implementing sql queries into Javafx - java

I wanted to ask a question about implementing SQL queries into a JavaFX application, specifically, I've been trying to create an "employee" application that connects to a MySQL database hosted in localhost. I'm using a DAO pattern to do this and the code is apparently right, the only problem I'm having is that I keep getting errors when trying to add a new employee to the table. Specifically, I'm getting an SQL syntax error and I have no idea what is wrong with the code.
I'll put the code for my EmployeeDAO class down there, please ignore the SQL errors in all the methods (I haven't corrected it yet), the method I already corrected and is still giving me problems is the insertEmp() method.
package Model;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import Util.DBUtil;
import java.sql.*;
public class EmployeeDAO {
//Select an Employee
public static Employee searchEmployee (String empId) throws SQLException, ClassNotFoundException{
String selectStmt = "SELECT * FROM employees WHERE employeeId="+empId;
try{
ResultSet rsEmp = DBUtil.dbExecuteQuery(selectStmt);
Employee employee = getEmployeeFromResultSet(rsEmp);
return employee;
}catch (SQLException e){
System.out.println("While Searching An Employee With "+empId+" Id, An Error Occurred");
e.printStackTrace();
throw e;
}
}
private static Employee getEmployeeFromResultSet(ResultSet rs) throws SQLException{
Employee emp = null;
if(rs.next()){
emp = new Employee();
emp.setEmployeeId(rs.getInt("EMPLOYEE_ID"));
emp.setFirstName(rs.getString("FIRST_NAME"));
emp.setLastName(rs.getString("LAST_NAME"));
emp.setEmail(rs.getString("EMAIL"));
emp.setPhoneNumber(rs.getString("PHONE_NUMBER"));
emp.setHireDate(rs.getDate("HIRE_DATE"));
emp.setJobId(rs.getString("JOB_ID"));
emp.setSalary(rs.getInt("SALARY"));
emp.setCommissionPct(rs.getDouble("COMMISSION_PCT"));
emp.setManagerId(rs.getInt("MANAGER_ID"));
emp.setDepartmentId(rs.getInt("DEPARTMENT_ID"));
}
return emp;
}
//Select Employees
public static ObservableList<Employee> searchEmployees() throws SQLException,ClassNotFoundException{
String selectStmt="SELECT * FROM employees";
try{
ResultSet rsEmps = DBUtil.dbExecuteQuery(selectStmt);
ObservableList<Employee> empList = getEmployeeList(rsEmps);
return empList;
}catch(SQLException e){
System.out.println("SQL Select Operation Failed");
e.printStackTrace();
throw e;
}
}
//Select * from employees operation
private static ObservableList<Employee> getEmployeeList(ResultSet rs) throws SQLException,ClassNotFoundException{
ObservableList<Employee> empList = FXCollections.observableArrayList();
while(rs.next()){
Employee emp = new Employee();
emp.setEmployeeId(rs.getInt("EMPLOYEE_ID"));
emp.setFirstName(rs.getString("FIRST_NAME"));
emp.setLastName(rs.getString("LAST_NAME"));
emp.setEmail(rs.getString("EMAIL"));
emp.setPhoneNumber(rs.getString("PHONE_NUMBER"));
emp.setHireDate(rs.getDate("HIRE_DATE"));
emp.setJobId(rs.getString("JOB_ID"));
emp.setSalary(rs.getInt("SALARY"));
emp.setCommissionPct(rs.getDouble("COMMISSION_PCT"));
emp.setManagerId(rs.getInt("MANAGER_ID"));
emp.setDepartmentId(rs.getInt("DEPARTMENT_ID"));
empList.add(emp);
}
return empList;
}
//Update an employee's email address
public static void updateEmpEmail(String empId, String empEmail) throws SQLException, ClassNotFoundException{
String updateStmt = "BEGIN\n" +
" UPDATE employees\n" +
" SET EMAIL = '" + empEmail + "'\n" +
" WHERE EMPLOYEE_ID = " + empId + ";\n" +
" COMMIT;\n" +
"END;";
try{
DBUtil.dbExecuteQuery(updateStmt);
}catch(SQLException e){
System.out.println("An Error Occurred While Updating The Information");
e.printStackTrace();
throw e;
}
}
public static void deleteEmpWithId(String empId) throws SQLException, ClassNotFoundException{
String updateStmt = "BEGIN\n" +
" DELETE FROM employees\n" +
" WHERE employee_id ="+ empId +";\n" +
" COMMIT;\n" +
"END;";
try{
DBUtil.dbExecuteQuery(updateStmt);
}catch(SQLException e){
System.out.println("An Error Occurred While Deleting An Employee With Id: "+empId);
e.printStackTrace();
throw e;
}
}
public static void insertEmp(String name, String lastName, String email) throws SQLException, ClassNotFoundException{
String updateStmt = "BEGIN\n" +
" INSERT INTO employees ('FIRST_NAME', 'LAST_NAME', 'EMAIL', 'HIRE_DATE', 'JOB_ID')\n" +
" VALUES\n" +
" (?, ?, ?, SYSDATE, 'IT_PROG');\n" +
" END;";
try{
DBUtil.dbPreparedStatement(updateStmt, name, lastName, email);
}catch(SQLException e){
System.out.println("An Error Occurred While Adding A New Employee To The Table");
e.printStackTrace();
throw e;
}
}
}
I'll also add down here the code that uses the insertEmp method.
public static void dbPreparedStatement(String sqlStmt, String name, String lastName, String email) throws SQLException,ClassNotFoundException{
PreparedStatement stmt = null;
try{
dbConnect();
stmt=conn.prepareStatement(sqlStmt);
stmt.setString(1, name);
stmt.setString(2, lastName);
stmt.setString(3, email);
stmt.execute();
}catch(SQLException e){
System.out.println("Error Occured At ExecutePreparedStatement Operation");
e.printStackTrace();
throw e;
}
dbDisconnect();
}

As shree mentioned, I made a mistake when writing down column names, I fixed that, also fixed an error regarding the SYSDATE() function being written mistakingly as only SYSDATE. The SQL still wouldn't work, so I took out the BEGIN and END lines and it works fine now, no idea why though.

Related

Getting Java mysql SQL Syntax error but my query seems normal

I am developing a simple java mysql based application and during data insertion into the database I'm getting an SQL error mentioned below.
Here is my code:
public DBConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&useLegacyDatetimeCode=false&serverTimezone=Turkey", "root", "");
st = con.createStatement();
System.out.println("CONNECTED!");
} catch (Exception e) {
System.out.println("Error : " + e);
}
}
public void addCustomer(String name, String surname, String company, String adress, String adressTwo){
String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;
try {
st.executeUpdate(addQuery);
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}
Here is my java main method that add's the data:
public static void main(String[] args) {
// TODO code application logic here
Customers c1 = new Customers();
c1.setIsim("test");
c1.setSoyisim("test");
c1.setSirket("test");
c1.setAdres("test");
c1.setIletisim("test");
DBConnection db = new DBConnection();
db.addCustomer(c1.isim, c1.soyisim, c1.sirket, c1.adres, c1.iletisim);
}
The error I'm getting is:
Error occured when adding value to database : java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''insert into musteri (ad,soyad,sirket,adres,iletisim) values (?,?,?,?,?)'' at line 1
You are mixing statements with prepared statements. You should use a prepared statement and set the values to it:
public void addCustomer(String name, String surname, String company, String address, String adressTwo) {
String addQuery = "insert into musteri (name, surname, company, adress, adressTwo) values (?,?,?,?,?)" ;
// Shown here for simplicitly.
// The query could be prepared once and stored in a data member
try (PreparedStatement ps = con.prepareStatement(addQuery)) {
ps.setString(1, name);
ps.setString(2, surname);
ps.setString(3, company);
ps.setString(4, address);
ps.setString(5, addressTwo);
ps.executeUpdate();
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}
May I suggest you implement addCustomer like this. Use a local Statement and create it by using try-with-resource style and then set your parameters for the query
public void addCustomer(String name, String surname, String company, String adress, String adressTwo){
String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;
try (PreparedStatement stmt = con.prepareStatement(addQuery)) {
stmt.setString(1, name);
stmt.setString(2, surname);
stmt.setString(3, company);
stmt.setString(4, adress);
stmt.setString(5, adressTwo);
stmt.executeUpdate();
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}

java.sql.SQLExecption:parameter index out of range (1>number of prameters, which is 0) for update sql

i have problem with my project, and it still new for me with MYSQL, i want to get data from database and do some calculation and update the value on it,
its like making withdraw function like ATM machine. This my table look like.
enter image description here . You can see constructor parameter that carry value (String value and String ID). For Value="100"; and ID="5221311" you can see it on my table picture.
public ConformWithdraw() {
initComponents();
try {
Class.forName("com.jdbc.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ConformWithdraw(String value,String ID) {
initComponents();
this.value=value;
this.ID=ID;
}
------------------------------------------------------------
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
+ "'";
PreparedStatement smtm = con.prepareStatement(validate);
ResultSet resultSet = smtm.executeQuery();
User user = null;
if (resultSet.next()) {
user = new User();
user.setBalance(resultSet.getString("accountBalance"));
double balance=Double.parseDouble(user.getBalance());
double val=Double.parseDouble(value);
total =(balance - val);
}
smtm.close();
resultSet.close();
program();
} catch (SQLException | HeadlessException | ClassCastException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
-------------------------------------------------------------
public void program(){
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = '"+String.valueOf(total)+"'"
+ "WHERE accountID = '"+ID+"'";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
id=Integer.parseInt(ID);
pstmt.setString(1, String.valueOf(total));
pstmt.setInt(2, id);
int rowAffected = pstmt.executeUpdate();
pstmt.close();
new ShowWithdraw().setVisible(true);
dispose();
}catch(SQLException | HeadlessException | ClassCastException ex){
JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null, "slh sini");
}
}
You are already setting the parameters on the query, so It tries to set the parameters and find no parameters to find. Try this:
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = ?"
+ "WHERE accountID = ?";

Why doesn't my Java code create a table in an in-memory SQLite database and print the table name?

I want to create an in-memory database and check that the table exists afterwards. Unfortunately, my code doesn't print anything to the console, so either the check for a table or the table creation process is wrong.
How do I fix it?
import java.sql.*;
public class Main {
private static String url = "jdbc:sqlite::memory";
private static void createNewTable(Connection conn) {
String sql = "CREATE TABLE IF NOT EXISTS students (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text NOT NULL"
+ ");";
try (Statement stmt = conn.createStatement();) {
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void checkTable(Connection conn){
String sql = "SELECT name FROM sqlite_temp_master WHERE type='table'";
try (Statement stmt = conn.createStatement();) {
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("table: " + rs.getString(1));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
Connection conn;
try{
conn = DriverManager.getConnection(url);
createNewTable(conn);
checkTable(conn);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}

Java - How can I INSERT values in SQLite?

Im starting in SQLite, I created my db and the connection works.
When I try to Insert a value (the db is empty) I get the following error:
java.sql.SQLException: near ".684": syntax error
import java.sql.*;
public class connection{
String route = "C:\\Freeman SA.db";
Connection c = null;
Statement stat = null;
String op;
public void connect(){
try{
c = DriverManager.getConnection("jdbc:sqlite:"+route);
if (c!=null)
System.out.println("Connected to db.");
}
catch (SQLException ex) {
System.err.println("Couldn't connect."+ex.getMessage());
}
}
public void insert_DB(String NAME, String LNAME, String ID, int AGE, int TIME, int SALARY) throws SQLException{
connect();
try {
stat = c.createStatement();
op = "INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES (" + NAME + ", " + LNAME + ", " + ID + ", " + AGE + ", " + TIME + ", " + SALARY + ");";
stat.executeUpdate(op); //Here is the problem
stat.close();
}
catch (SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
c.close();
}
}
Main.
public static void main(String[] args) throws IOException {
connection n = new connection();
try {
n.insert_DB("Charlie", "White", "18.954.621-K", 21, 2, 650000);
} catch (SQLException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
PD: I'm learning from here: http://www.tutorialspoint.com/sqlite/sqlite_java.htm
It's a bad idea to create a SQL statement by concatenating Strings like that. Do some research into SQL injection attack and Little Bobby Tables.
PreparedStatement is a better idea. Bind your variables after validation.
See if this makes your life better:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Demo RenumerationDao
* Created by Michael
* Creation date 6/8/2016.
* #link https://stackoverflow.com/questions/37714254/java-how-can-i-insert-values-in-sqlite/37714292#37714292
*/
public class RenumerationDao {
private static final String INSERT_SQL = "INSERT INTO Remuneraciones(Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES(?, ?, ?, ?, ?, ?)";
private Connection connection; // Better to get this from a pool.
public RenumerationDao(Connection connection) {
this.connection = connection;
}
public int insert(String firstName, String lastName, String id, int age, int timeInHours, int salary) {
int numRowsInserted = 0;
PreparedStatement ps = null;
try {
ps = this.connection.prepareStatement(INSERT_SQL);
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setString(3, id);
ps.setInt(4, timeInHours);
ps.setInt(5, age); // You'll have to update this each and every year. BirthDate would be better.
ps.setInt(6, salary);
numRowsInserted = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(ps);
}
return numRowsInserted;
}
public static void close(Statement statement) {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

java.sql.SqlException: no data found while inserting the data into table

I am trying to inserting the data into the table using ms access 2007 but getting the exception "java.sql.SqlException: no data found"
My data souce name is employee
import java.sql.*;
class AccessDatabase
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection ("jdbc:odbc:employee");
Statement st = con.createStatement();
String name = "roseindia";
String address = "delhi";
int i = st.executeUpdate("insert into user(name,address) values
('" + name + "','" + address + "')");
System.out.println("Row is added");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I think you don't have a database created. Following code should work:
import java.sql.*;
class ExecuteSqlQuery {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
String str = "CREATE TABLE user(id INTEGER, " + "name VARCHAR(25), address VARCHAR(100), primary key(id))";
st.executeUpdate(str);
System.out.println("Table is created into the database.");
st.executeUpdate("insert into user(id,name,address) values(1111,'roseindia','Rohini,Delhi')");
System.out.println("Row is inserted.");
st.close();
con.close();
}
catch (Exception ex) {
System.out.println("Unable to connect to database.");
}
}
}

Categories