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
Related
I am writing a JSP application where the user enters a food item and it is entered in a PostgreSQL database. I had no problems implementing this when the user manually had to enter the next primary key, but I removed this ability so that the primary key would be automatically assigned when the enter button is clicked. I would like the query to fetch the current maximum FID (Food ID) and set the new food item's FID to the previous + 1.
try {
conn = ConnectionProvider.getCon();
String sql = "select fid from project.food order by fid desc limit 1";
pst = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
status = pst.getResultSetType();
f.setFood_id(status + 1);
pst = conn.prepareStatement("insert into project.food values(?,?,?,?,?,?)");
pst.setInt(1, f.getFood_id());
pst.setString(2, f.getFood_name()); //set name
pst.setInt(3, f.getCount()); //set count
pst.setInt(4, f.getPrice_per_item()); //set price
pst.setInt(5, f.getThreshold()); //set threshold
pst.setString(6, "false");
status = pst.executeUpdate();
conn.close();
pst.close();
} catch (Exception ex) {
System.out.println(ex);
}
return status;
}
The first food item is successfully inserted into the database in row 1006, instead of the 7th row, which is the first available in the database. Additionally, the second insert fails due to the failure of the primary key to the incremented by 1. The program again tries to insert the next tuple in the same row and thus violates the primary key constraint.
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "food_pkey"
Detail: Key (fid)=(1006) already exists.
Make your primary key autoincrement in the database by declaring it SERIAL datatype (basically an auto incrementing INT) so a sequence is created to automatically assign values to it.
Then convert your update statement to specify all columns except for the primary key (i.e. insert into project.food(foo, bar, baz) values (?, ?, ?), and remove one ? placeholder and the pst.setInt(1,f.getFood_id()); line. This will insert values to all the other columns, and the primary key will be generated by the database.
This way you don't need to do a select when you want to insert (which was a really bad idea anyway), and you let the database do what it does best. You don't need to care about the value of the primary key after that.
I'm working with Java JDBC with Apache Derby data base.
I have a table called `company`` with the values :
id, comp_name, password, email.
This method should create a new row of company with name, password, and email received from the user but the ID should be given automatically from the database and increment itself each time a new company is added to the database.
I just can't figure out how to make this work, I obviously get a error
"column 'ID' cannot accept a NULL value."
because the update occours before the ID is setted.
Code:
public void createCompany(Company company) {
Connection con = null;
try {
con = ConnectionPool.getInstance().getConnection();
String sql = "INSERT INTO company (comp_name, password, email) VALUES (?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, company.getCompName());
pstmt.setString(2, company.getPassword());
pstmt.setString(3, company.getEmail());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
company.setId(rs.getLong(1));
pstmt.getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionPool.getInstance().returnCon(con);
}
During creation of that table you have to write following DDL
CREATE TABLE MAPS
(
comp_id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(24) NOT NULL,
password VARCHAR(26)
)
Ref : https://db.apache.org/derby/docs/10.0/manuals/develop/develop132.html
You're doing almost everything right, you just need to let the database assign an unique ID to each inserted row:
CREATE TABLE my_table (
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
...
);
A problem could be that you made a mistake by creating your table.
You could create your table like this:
CREATE TABLE company
(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(50),
email VARCHAR(50),
password VARCHAR (50)
)
IF you want other values to be not NULL you could add NOT NULL to their lines:
password VARCHAR (50) NOT NULL
Delte your old table and execute the the SQl above on your DB. After that you can use your code without changes.
Here is my code I am getting the following error"java.sql.sqlException:no such column: employID" and I have rechecked my db table column name is correct employID nothing wrong with that but still getting the same error please help I am trying to load the table data based on the first column into a textboxes using netbeans IDE and sqlite database.
private void tableEmployeeMouseClicked(java.awt.event.MouseEvent evt) {
try{
int row=tableEmployee.getSelectedRow();
String tableClick=(tableEmployee.getModel().getValueAt(row, 0).toString());
String sql="SELECT * FROM employeeInfo WHERE employID=' "+tableClick+" ' ";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
String add1=rs.getString("employID");
empid.setText(add1);
String bdd=rs.getString("name");
name.setText(bdd);
String cdd=rs.getString("surname");
surname.setText(cdd);
String ddd=rs.getString("age");
age.setText(ddd);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
n.b. the employID column in my database is set
to INTEGER can that or my query inside my code have any connection with the error type..
Thanks.
EDIT: The DDL sentence
CREATE TABLE "employeeInfo" (
"employID " INTEGER PRIMARY KEY NOT NULL ,
"name" CHAR, "surname" CHAR,
"age" INTEGER, "username" VARCHAR, "password" VARCHAR)
From the error it is clear that the resultset does not have the column named 'employID'. To troubleshoot this issue you can do either of these:
1. Inspect the resultset metadata and look at the column names that you are getting.
2. Or use column position in resultset.getString() methods to get the values and verify if you are getting employID values.
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
I have a method which insert a record to mysql database as bellow,
public boolean addOrganization(OrganizationDTO organizationDTO) {
Connection con = null;
try {
String insertOrganizationSQL = "INSERT INTO organizations (org_id, org_name) VALUES(?, ?)";
con = JDBCConnectionPool.getInstance().checkOut();
PreparedStatement insertOrgPS = (PreparedStatement) con.prepareStatement(insertOrganizationSQL);
insertOrgPS.setString(1, organizationDTO.getOrg_id());
insertOrgPS.execute();
return true;
} catch (Exception e) {
JDBCConnectionPool.getInstance().checkIn(con);
logger.error(e.getLocalizedMessage());
e.printStackTrace();
return false;
} finally {
JDBCConnectionPool.getInstance().checkIn(con);
}
}
database table,
CREATE TABLE `organizations` (
`org_id` varchar(5) NOT NULL,
`org_name` varchar(100) DEFAULT NULL,
`sys_dat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`user` varchar(100) NOT NULL,
PRIMARY KEY (`org_id`)
)
what I need is, when I insert a new record if, that is a duplicate exit the method without trying to insert and inform the user that it is a duplicate record. Is it possible to do without writing another method to search the record before inserting?
I would add a UNIQUE constraint to your table. For example, if org_name needs to be unique:
ALTER TABLE organizations ADD UNIQUE (org_name);
Then observe what's returned when you try to insert a duplicate record through Java. Add code to check for this, and if it occurs, display the message to your user.
Here is the reference documentation for ALTER TABLE.
Thats right, Alter table will surely help.
In your case, let say, both org_id and org_name is there, I would add unique in both, just avoid any confusion later.