I have 3 buttons (add, save, cancel). If I press the add button, it automatically generates an auto-incremented value and is displayed in a text field. If I press the save button, it updates the record. My problem is when I press the cancel button, I want to be able to delete the current data added and set the auto-increment key to the primary key of the deleted data. Is it possible to do this?
dc.connect();
try {
PreparedStatement st=dc.getConnection().prepareStatement("Delete from Employeemaster where empno = '" + empno.getText() + "'");
i=st.executeUpdate();
if (i>0) {
dc.getConnection().commit();
}
} catch (Exception e) {
JOptionPane msg=new JOptionPane();
msg.showMessageDialog(this,"Database Error: "+e.getMessage());
}
dc.disconnect();
dc.connect();
try {
PreparedStatement st=dc.getConnection().prepareStatement("ALTER TABLE employeemaster AUTO_INCREMENT ='" + empno.getText() + "'");
i=st.executeUpdate();
if (i>0) {
dc.getConnection().commit();
}
} catch (Exception e) {
JOptionPane msg=new JOptionPane();
msg.showMessageDialog(this,"Database Error: "+e.getMessage());
}
I tried replacing
ALTER TABLE employeemaster AUTO_INCREMENT ='" + empno.getText() + "'"
into
ALTER TABLE employeemaster AUTO_INCREMENT = 10003;
and it worked. Is it possible to set the auto-incremented value to the one contained/entered in a textfield?
Additional info:
The error I get is
"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 "10003" at line 1."
The use of single quote will cause mysql cast the auto_increment value (integer) into string, which is not desirable
Strip the single quote, like
"ALTER TABLE employeemaster AUTO_INCREMENT=" + empno.getText()
Or
cast empno.getText() into integer
Related
I am trying to insert data into a CUSTOMER table.
private void c_enterActionPerformed(java.awt.event.ActionEvent evt) {
String insertSQL = "insert into CUSTOMER(CUST_ID, CUST_NIC, CUST_FNAME,CUST_LNAME, CUST_EMAIL, CUST_ADDRESS, CUST_PHONE, CUST_IMG) values(?,?,?,?,?,?,?,?)";
try{
ps = con.prepareStatement(insertSQL);
ps.setString(1,c_id_text.getText());
ps.setString(2,c_nic_text.getText());
ps.setString(3,c_fname_text.getText());
ps.setString(4,c_lname_text.getText());
ps.setString(5,c_email_text.getText());
ps.setString(6,c_address_text.getText());
ps.setString(7,c_phone_text.getText());
ps.setString(8,img_path_txt.getText());
ps.execute();
JOptionPane.showMessageDialog(null, "New Customer Inserted\nCongratulations!");
c_id_text.setText("");
c_nic_text.setText("");
c_fname_text.setText("");
c_lname_text.setText("");
c_email_text.setText("");
c_address_text.setText("");
c_phone_text.setText("");
img_path_txt.setText("");
updateTable();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Insertion error: "+e);
}
}
The table was created using:
CREATE TABLE CUSTOMER(
CUST_ID INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
CUST_NIC VARCHAR(14),
CUST_FNAME VARCHAR(20),
CUST_LNAME VARCHAR(25),
CUST_EMAIL VARCHAR(45),
CUST_ADDRESS VARCHAR(60),
CUST_PHONE INTEGER,
CUST_IMG VARCHAR(100));
SELECT * FROM AKASH.CUSTOMER FETCH FIRST 100 ROWS ONLY;
I have disabled the CUST_ID text as shown. It's telling me "Attempt to modify an identity column 'CUST_ID'.
Now, for claritfication: I know what is happening. But I don't know how to fix it.
I tried to remove ps.setString(1,c_id_text.getText()); , that didn't work.
I also tried to remove CUST_ID from String insertSQL... , but to no avail.
If I try to input data from the SQL using "Insert row" button, it works and the CUST_ID column displays ""
Found my mistake. Solved after commenting out
ps.setString(1,c_id_text.getText());
and c_id_text.setText("");
as well as removing CUST_ID form the insertSQL line of code.
I am making a javafx (intelliJ with java jdk 11) app using SQLite version 3.30.1 with DB Browser for SQLite.
I have a table called "beehives" and each beehive can have diseases (stored in the table "diseases").
this is my "beehives" table:
CREATE TABLE "beehives" (
"number" INTEGER NOT NULL,
"id_apiary" INTEGER NOT NULL DEFAULT -2,
"date" DATE,
"type" TEXT,
"favorite" BOOLEAN DEFAULT 'false',
PRIMARY KEY("number","id_apiary"),
FOREIGN KEY("id_apiary") REFERENCES "apiaries"("id") ON DELETE SET NULL
);
this is my "diseases" table:
CREATE TABLE "diseases" (
"id" INTEGER NOT NULL,
"id_beehive" INTEGER NOT NULL,
"id_apiary" INTEGER NOT NULL,
"disease" TEXT NOT NULL,
"treatment" TEXT NOT NULL,
"start_treat_date" DATE NOT NULL,
"end_treat_date" DATE,
PRIMARY KEY("id"),
FOREIGN KEY("id_beehive","id_apiary") REFERENCES "beehives"("number","id_apiary") ON UPDATE CASCADE
);
this is my "apiaries" table in case you need it:
CREATE TABLE "apiaries" (
"id" INTEGER NOT NULL,
"name" TEXT NOT NULL,
"address" TEXT,
PRIMARY KEY("id")
);
Everything works fine, but when I update a beehive (for example when I update the "number", which is the primary key in beehives table) the diseases does not update the number. The result is that the diseases get some kind of disconnected since the beehive change his "number" correctly, but the disease doesn't update it. There is no error message.
My java method that calls the update is:
public void updateBeehiveInDB(Beehives newBeehive,Beehives oldBeehive){
try {
s = "UPDATE beehives SET number=?, id_apiary=?, date=?, type=?, favorite=? WHERE number=? and id_apiary=? ";
preparedStatement = connection.prepareStatement(s);
preparedStatement.setInt(1, newBeehive.getNumber());
preparedStatement.setInt(2, newBeehive.getId_apiary());
preparedStatement.setDate(3, newBeehive.getDate());
preparedStatement.setString(4, newBeehive.getType());
preparedStatement.setBoolean(5, newBeehive.isFavorite());
preparedStatement.setInt(6, oldBeehive.getNumber());
preparedStatement.setInt(7,oldBeehive.getId_apiary());
int i = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
I tried to check if foreign keys are "on" following the SQLite documentation here, but my English is not good enough and I am using DB Manager. So no idea how to check if this is on, or how to turn it on manually.
What can I do to update the diseases "id_beehives" when I update "number" on beehives table?
The problem was that i am using a composite foreign key and i need to implement it correctly on other tables too even if i was not using them yet in this new project. Was very hard to find the problem because intellij normally show all the SQL error messages, but in this case, it was not showing anything. But when i tried to do the SQL sentence manually in the DB Browser, there i got an error message and was able to fix it.
Also had to activate foreign key on the connection:
public Connection openConnection() {
try {
String dbPath = "jdbc:sqlite:resources/db/datab.db";
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
connection = DriverManager.getConnection(dbPath,config.toProperties());
return connection;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
I need some help.
We get an assignment and the teacher required that we use associations and not using keys/ids. I don't really understand the concept, and how I solve it using SQL database. What I had learned in the database course that we use keys/id to link the tables together. A brief deception of the problem, we have a yacht club, in the club, we can register, delete and edit member. For every member, we can register one or more boat. A member can edit and delete a boat. The problem Should be solved by Model-View separation.
I have solved the problem by creating two tables and link the boat table to the member by memberId. The teacher told me it is not correct to use ID(He said: Basically the UI should add Boats to a Member object, not insert boats in a database with a member id). Can you please give me suggestions on how to solve the issue without using Id.
public void createTables() {
Statement tablesSt;
try {
tablesSt = conn.createStatement();
tablesSt.executeUpdate( "CREATE TABLE IF NOT EXISTS "+ Boat +
" (Boat_ID INT PRIMARY KEY," +
" Member_ID INT NOT NULL,"+
" Size INT NOT NULL ,"+
" Type TEXT NOT NULL ,"+
" FOREIGN KEY (Member_ID) REFERENCES " + Member + "(Member_ID) ON DELETE CASCADE) ");
tablesSt.close();
tablesSt = conn.createStatement();
tablesSt.executeUpdate( "CREATE TABLE IF NOT EXISTS "+ Member +
" (Member_ID INT PRIMARY KEY," +
" Member_Name TEXT NOT NULL ," +
" Personal_Number INT UNIQUE )");
tablesSt.close();
A code from boat class
public void newBoat(int memberID, String type, int size ) {
int BoatId= 0;
try {
ResultSet rc= Control.conn.createStatement().executeQuery("SELECT * FROM Boat ORDER BY Boat_ID DESC LIMIT 1");
BoatId =rc.getInt("Boat_ID") +1;
Statement registerBoat = Control.conn.createStatement();
registerBoat.executeUpdate("INSERT OR IGNORE INTO Boat VALUES("+BoatId+" , "+memberID+" , '"+size+"', '"+type+"')");
Control.conn.commit();
Control.conn.setAutoCommit(false);
/* ResultSet rs2 = Control.conn.createStatement().executeQuery(" SELECT * FROM Boat WHERE Boat_ID ="+ BoatId);
System.out.println(rs2.getString("type"));*/ // test code to check if the Boat is Succesfully registered
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I've been trying to use this code to create a table in a database that the code before this created successfully.
//Creates "Parts" Table if it's not already created.
public void createTableIfNecessary() throws SQLException{
String createString =
"USE inventory; " +
"CREATE TABLE IF NOT EXISTS parts " +
"(part_name TEXT NOT NULL, remaining_amt INT NOT NULL, " +
"restock_amt INT, barcode TEXT, location TEXT, part_id INT NOT NULL AUTO_INCREMENT);";
Statement createTable = this.con.createStatement();
createTable.execute(createString);
System.out.println("Table created or already existed: Parts");
}
My code to connect to the Database server:
try{Class.forName("com.mysql.jdbc.Driver");} catch(Exception e){
e.printStackTrace();
}
this.con = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
this.con = DriverManager.getConnection("jdbc:mysql://" + this.serverName + ":" + this.portNumber + "/", connectionProps);
System.out.println("Connected to MySQL Database Server");
(This works, but it may be helpful to see)
My 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 'CREATE TABLE IF NOT EXISTS parts (part_name TEXT NOT NULL, remaining_amt INT NOT' at line 1
I Assume it is just my incompetence with MySQL, but maybe someone here can see my syntax error. Thanks!
The USE inventory; statement is not appropriate in the context of a JDBC connection. You need to use Connection#setCatalog() to switch to a particular db. For more details, see
Java, how to change current database to another?
So do that and remove the USE clause from your SQL.
For auto_increment column in mysql, it has to be indexed. So you have to index part_id by making it a primary key or unique.
CREATE TABLE IF NOT EXISTS parts
(part_name TEXT NOT NULL,
remaining_amt INT NOT NULL,
restock_amt INT,
barcode TEXT,
location TEXT,
part_id INT NOT NULL AUTO_INCREMENT,
primary key (part_id));
When I enter data with my java program (simple dictionary ) it throws an error:
MySQLIntegrityConstraintViolationException: Cannot add or update a
child row: a foreign key constraint fails (singlehaw.card,
CONSTRAINT card_ibfk_1 FOREIGN KEY (wordId) REFERENCES word
(wordId))
But when I enter data through query in command prompt I don't face any problem.
here I post my method:
public boolean insert(Card card) {
Connection connection = MySqlUtils.getInstance().getConnection();
PreparedStatement statement = null;
ResultSet resultSet = null;
int cardId = -1;
try {
String INSERT_INTO_TABLE_CARD_QUERY = "INSERT INTO "
+ TBL_CARD + " ("
+ STATUS + ", "
+ RATING + ", "
+ INSERT_TIME + ", "
+ DIC_ID + ", "
+ WORD_ID
+ ") VALUES (?,?,NOW(),?,?)";
statement = connection.prepareStatement(INSERT_INTO_TABLE_WORDS_QUERY, Statement.RETURN_GENERATED_KEYS);
statement.setString(1, card.getStatus().name());
statement.setInt(2, card.getRating());
statement.setInt(3, card.getDictionaryId());
statement.setInt(4, card.getWordId());
statement.execute();
// get last inserted id
resultSet = statement.getGeneratedKeys();
if (resultSet.next())
cardId = resultSet.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
card.setCardId(cardId);
return true;
}
and also scripts of creating tables:
CREATE TABLE dictionary (
dictionaryId SERIAL,
dictionary VARCHAR(128) NOT NULL,
PRIMARY KEY (dictionaryId)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE word (
wordId SERIAL,
word VARCHAR(255) NOT NULL UNIQUE,
transcription VARCHAR(255),
PRIMARY KEY (wordId)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE card (
cardId SERIAL,
status ENUM ('EDIT', 'POSTPONED', 'TO_LEARN', 'LEARNT') NOT NULL DEFAULT 'TO_LEARN',
rating TINYINT DEFAULT '0' NOT NULL,
insert_time TIMESTAMP DEFAULT NOW(),
update_time TIMESTAMP,
dictionaryId BIGINT UNSIGNED NOT NULL,
wordId BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (cardId),
FOREIGN KEY (wordId) REFERENCES word (wordId),
FOREIGN KEY (dictionaryId) REFERENCES dictionary (dictionaryId) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Perhaps, the fact your wordID fields on the tables have different data types is affecting your program. SERIAL is an alias for Bigint. Idea discarded.
Print somwehere in the logs the actual statement being executed. Maybe there's something that's not being included.
Thnx guys a lot. Understood many things from this topic. Right now the problem has gone. The problem was due to populating tables via JUnit tests and because of maven my tests gone in a wrong order so it was difficult to recognize the real problem.
You can switch off your constraints ,execute your query, and switch constraints on.
SET FOREIGN_KEY_CHECKS=0;
... here is your sql ...
SET FOREIGN_KEY_CHECKS=1;