Need some modification in my code - java

This is a small part of the application where user can register any number of employees and employee id is generated by using a while loop....As i close the application & start filling the data again in second round...the value of employee id empid resets to zero. Well, as long as the application is running, i get the desired o/p i.e. a unique id is allotted to every employee. I dont want empid's value to start from 0 whenever i start the application. Need alternatives and/or any modification. Code is provided here
int empcount=0;
public void actionPerformed(ActionEvent ae) {
//---------------------If user wants to add data
if(ae.getActionCommand()=="ADD EMPLOYEE") {
System.out.println("ADDING");
try{
empcount=empcount+1;//----------------will assign employees with unique emp id
//--------------------returns the text in name field to variables
String s_name=name.getText();
int s_code=empcount;
String s_dept=dept.getText();
String s_ph=ph.getText();
String s_bg=bg.getText();
String s_add=add.getText();
String s_date=date.getText();
PreparedStatement st=null;
Connection con = null;
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/", "SA", "");
st=con.prepareStatement("Insert into EmpReg (emp_name,emp_code,emp_ph,emp_bg,emp_add,emp_date,b_id) values(?,?,?,?,?,?,?)");
//---------------------parameters and respective values, passed to the SQL statement
st.setString(1,s_name);
st.setInt(2,s_code);
st.setString(3,s_ph);
st.setString(4,s_bg);
st.setString(5,s_add);
st.setString(6,s_date);
st.setString(7,s_dept);
st.execute();
JOptionPane.showMessageDialog(null,"Data is inserted into the database");
JOptionPane.showMessageDialog(code, "employee code"+ empcount+"");
con.close();
}
catch(Exception Ee){
System.out.println(Ee);
}
}
}
});

The standard SQL way of doing this, is having an "autoincrement" primary key (emp_code), for hsqldb see IDENTITY.
In the SQL INSERT statement leave out the primary key. Now the database generates a unique new key.
After the execution, you can retrieve the generated primary key from the statement with getGeneratedKeys.
This ensures that two parallel processes will not mess up the primary keys.

Why don't you create a field in your DB, that is set to autoIncrementTrue and maybe use it as ID as well. You can also use this field as Employee-Number.
You can check this Link for more Information: http://www.w3schools.com/sql/sql_autoincrement.asp
The generated number will increment every time you insert a new Employee.

You could use a DB like Oracle, MySQL, PostGre and use a Sequence or auto generated ID Column to do that for you

Related

arabic data problem when it inserts from the java application (mysql , javafx)

I have a problem when I enter data from the application to mysql database, it appears in the form of "????" However, when I enter data via "phpmyadmin" the data appears normally
well the problem is when i enter data via application ,
not related with database
any way i tried to change the encode of database and the table and the fields inside the tables
here the insert query in my application
public static void dbConnect() {
try{
Class.forName(DRIVER);
connector = DriverManager.getConnection(DATA_BASE_BATH, "root", "");
insert = connector.prepareStatement("INSERT INTO students VALUES (?,?,?,?)");
}
public static void insert(int id , String name , String special , double gpa){
dbConnect();
try{
insert.setInt(1, id);
insert.setString(2, name);
insert.setString(3,special);
insert.setDouble(4,gpa);
insert.execute();
}
catch(SQLException e){
System.out.println(e.getMessage());
}
}
here the image to understand the problem
-the first row is the data entry from the application
-and the second row is the data entry manually from the phpmyadmin
Your application isn't properly handling the data.
You need to set the charset during the connection to the MySQL server.
Perhaps by running the command SET NAMES 'UTF8'; as part of your connection script.
This answer states that you can even make it part the JDBC connection string in DATA_BASE_BATH when referenced in your getConnection() function call, as does this one.

How to fix 'terminated' while using rs.getString

When trying to pull from an SQL database, I get in Java console.
I am able to enter my ID manually in the prepareStatement, but I can't use setString to work with with the prepareStatement.
I haven't throught of too much to try, but I did find that the issue is within the while statement. rs.next returns false when it should return true. The information in SQL has been committed, and I can call all of the information in java using a function that reads out the entire table.
getemployeeDataById("01");
private static void getemployeeDataById(String e_id) {
DBConnection dbConnection = DBConnection.getInstance();
PreparedStatement ps;
try {
ps = dbConnection.getConnection().prepareStatement("select * from employee where E_ID = ?");
ps.setString(1, e_id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("ename"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
SQL
CREATE TABLE EMPLOYEE
(E_ID CHAR(3) PRIMARY KEY,
ENAME CHAR(25),
DOB CHAR(25),
EMAIL CHAR(25),
PHONE CHAR(25),
ADDRESS CHAR(25));
INSERT INTO EMPLOYEE
VALUES
('01','JEREMY MANN','12/23/1992','jeremy#jeremy.com','317-528-1234','123 CandyCane Lane');
I am expecting to get the name outputted in the console, so for this example it would be "JEREMY MANN." The code runs and then in the Eclipse Java console it shows Application [Java Application]. It runs into an issue within the while statement, but I'm not sure what's causing rs.next to be false.
In Oracle 11g (well, Oracle versions generally) CHAR is a fixed width type, and if you give it a value shorter than the given width, it will be padded with blanks (which might not be obvious if you just dumped the table contents). In this case, your key is length 3, but the string "01" is length 2, so that won't work.
Try VARCHAR2 for the column types, that's a variable length string.

error while inserting data inside mysql table

String pass=new String(pf1.getPassword());
try {
Connection myConn=DriverManager.getConnection("jdbc:mysql://localhost:3306/javaproject","root","noor1032");
PreparedStatement myStat=myConn.prepareStatement("insert into user_info (username,password,email_id)"+"values(?,?,?)");
myStat.setString(1, tf1.getText());
myStat.setString(2, pass);
myStat.setString(3, tf2.getText());
myStat.execute();
myConn.close();
}
catch(Exception f)
{
System.err.println("Got an exception!");
System.err.println(f.getMessage());
}
I want to insert data entered by user in a JFrame to my sql database. tf1 and tf2 are textfields for username and email_id, respectively. When I execute this statement an exception occurs saying that
Field 'id' does not have a default value
id is a column in my database denoting numbers like 1,2,3 and so on. Please help me.
You have to set the ID as Auto Increment in mysql .It will work
Although you haven't shared your table's structure, I guess that id is a PRIMARY KEY but you missed AUTO_INCREMENT configuration. In your database, run the following statement
ALTER TABLE user_info MODIFY COLUMN id INT auto_increment

In this program, I have to set already existing value for ssn in where clause (ie: in setString (3, ) )

public void UpdateCustomer(Customer customer) throws CustomerHomeException, ClassNotFoundException{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Mydb";
String user = "user1";
String password = "password";
Connection con = DriverManager.getConnection(url,user,password);
PreparedStatement smt= con.prepareStatement("update customer SET ssn = ? customer_name = ? where ssn = ?");
if(getCustomer.equals(customer.getSocialSecurityNumber()))
smt.setString(1,customer.getSocialSecurityNumber());
smt.setString(2, customer.getName());
smt.setString(3, customer.);
smt.executeUpdate();
smt.close();
con.close();
}
catch (SQLException e){
throw new CustomerHomeException("Failed to create CustomerHome", e);
}
}
but I am confused how can i retrieve value for existing ssn. Also I have a method getCustomers to retrieve a particular customer separately. Will that help
I recommend that you revisit your database model. You are using SSN as a primary-key (based on you WHERE clause), but then you're trying to update it. It is EXTREMELY poor practice to update primary keys (ref: https://stackoverflow.com/a/3838649/2065845). If you introduce some other key value (an auto-incrementing ID perhaps?), then you'll be able to modify your update statement's WHERE clause to use that ID, and the fact that you no longer have the old SSN becomes unimportant.
Barring that, you'll either need to modify your method signature to include the old SSN, or you'll need to execute a SELECT with some other value to get the old SSN (though, if you can do that, I have to wonder why you don't just use that in the WHERE clause of your UPDATE statement).

Max value from auto commit false table

My problem is i have set a table auto commit false. I need to get the max id from that table(the currently inserted value of auto increment id). But i am getting the id of the previous committed process. Is it possible to get the value
My real problem is i need to insert into table some values, And need to take the id of the last inserted record from the first table and insert it to the second. The second insertion includes some image upload as well(as part of the code). so it take some delay or can have exceptions. I need to undo all insertions(both in the first and second) by occurring any exceptions. I tried to use commit-roll back method for this. But its not properly working as i mentioned above. main portion of my code is written below
try
{
//getting connection and setting auto commit false
dbHandler dbGetConnect=new dbHandler();
Connection conRegPlot=null;
conRegPlot=dbGetConnect.getconn();
conRegPlot.setAutoCommit(false);
String qryInsertPlot="INSERT INTO property_table(name,message,owner,locality,lattitude,longitude,country,state,city,type,catagory,created,modified,creted_date,zoompoint,mob_no,title,img_path,expire_date,lease_term) VALUES('none','"+description+"','"+sessionUserId+"','"+locality+"','"+lattitude+"','"+longitude+"','"+country+"','"+state+"','"+city+"','"+type+"','"+catagory+"',NOW(),NOW(),CURDATE(),'"+zoom+"','"+mob_no+"','"+title+"','NOT IN USE',"+expireDate+",'"+termsAndConditions+"')";//insertion into the first table
Statement stCrs=conRegPlot.createStatement();
int resp=stCrs.executeUpdate(qryInsertPlot);
String qryGetMaxProperty="SELECT MAX(l_id)"+
" FROM property_table"+
" WHERE stat='active'"+
" AND CURDATE()<=expire_date";
propertyId1=dbInsertPropert.returnSingleValue(qryGetMaxProperty);// get the max id
String qryInsertImage="INSERT INTO image_table(plot_id,ownr_id,created_date,created,modified,stat,img_path) VALUES('"+propertyId1+"','"+sessionUserId+"',CURDATE(),NOW(),NOW(),'active','"+img_pth+"')";
Statement stImg=conRegPlot.createStatement();
stImg.executeUpdate(qryInsertImage);// inserting the image
conRegPlot.commit();
}
catch(Exception exc)
{
conRegPlot.rollback();
}
finally{
conRegPlot.close();
}
Since
And need to take the id of the last inserted record from the first
table and insert it to the second.
You could the use of the new JDBC 3.0 method getGeneratedKeys() for get the generated ID. In ahother hand, you should use PreparedStatement for avoid SQL Injection.
PreparedStatement ps = null;
try {
conn = getConnection();
ps = conn.prepareStatement(myQuery, PreparedStatement.RETURN_GENERATED_KEYS);
ps.setInt(1, anInteger);
...
int rows = ps.executeUpdate();
if (rows == 1) {
ResultSet keysRS = ps.getGeneratedKeys();
if (keysRS.next())
int id = keysRS.getInt(1) // Get generated id
For MySQL, see more in http://dev.mysql.com/doc/refman/5.1/en/connector-j-usagenotes-last-insert-id.html#connector-j-examples-autoincrement-getgeneratedkeys

Categories

Resources