Okay, so I just started JDBC with derby client and I'm kind of new with it.
I set column ID as primary key with int as it's data type. However, I'm not sure if I should include myStatement.setString(1, ?); because I thought it should Auto Increment but it looks like it's not doing it.
Here's my Grab file details:
create table "ADMIN1".STUDENTPERSONALDETAILS
(
ID INTEGER not null primary key,
STUDENTID VARCHAR(10) not null,
LASTNAME VARCHAR(50) not null,
FIRSTNAME VARCHAR(50) not null,
MIDDLENAME VARCHAR(50) not null,
PLACEOFBIRTH VARCHAR(200) not null,
DOB VARCHAR(50) not null,
GENDER VARCHAR(4) not null,
CIVILSTATUS VARCHAR(7) not null,
RELIGION VARCHAR(15) not null,
NATIONALITY VARCHAR(20) not null
)
How can I correct my PreparedStatement or My Table in such a way that adding of value for column ID will be automatic so that I can start setString(2, studentID) and avoid getting error about the number of columns not matching with what was supplied?
Here's my code:
addButton.addActionListener(new ActionListener () {
#Override
public void actionPerformed(ActionEvent e) {
try {
String myDbUrl = "jdbc:derby://localhost:1527/Enrollment"; //stores url to string
String userName = "admin1";
String Password = "admin1";
Connection myDBConnection = DriverManager.getConnection(myDbUrl, userName, Password);
String myQuery = "INSERT INTO STUDENTPERSONALDETAILS"
+ "(STUDENTID,LASTNAME,FIRSTNAME,MIDDLENAME,PLACEOFBIRTH,DOB,GENDER,CIVILSTATUS,RELIGION,NATIONALITY) "
+ "VALUES(?,?,?,?,?,?,?,?,?,?) ";
String adminissionNo ;
String studentID = tfStudentId.getText().toString();
String lastName = tfLastName.getText().toString();
String firstName = tfFirstName.getText().toString();
String middleName = tfMiddleName.getText().toString();
String placeOfBirth = tfPob.getText().toString();
String dateOfBirth = listDOB.getSelectedItem().toString();
String gender = listGender.getSelectedItem().toString();
String civilStatus = listCivilStatus.getSelectedItem().toString();
String religion = listReligion.getSelectedItem().toString();
String nationality = listNationality.getSelectedItem().toString();
PreparedStatement myStatement = myDBConnection.prepareStatement(myQuery);
myStatement.setString(2, lastName);
myStatement.setString(3, firstName);
myStatement.setString(4, middleName);
myStatement.setString(5, placeOfBirth);
myStatement.setString(6, dateOfBirth);
myStatement.setString(7, gender);
myStatement.setString(8, civilStatus);
myStatement.setString(9, religion);
myStatement.setString(10, nationality);
boolean insertResult = myStatement.execute();
if(insertResult == true)
JOptionPane.showMessageDialog(null, "Successfully Added Information");
else
JOptionPane.showMessageDialog(null, "Encountered an error while inserting data");
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
}
});
Is it necessary to include myStatement.setString(1, integervaluehere) for Primary Keys? Isn't it supposed to autoincrement?
I'd appreciate any explanation because I just started learning the basics of PreparedStatements recently.
I tried counting the columns and tried 10 and 11 lines of myStatement.setString(), but still can't get it to insert data because of mismatch.
Thanks in advance.
You need to mention 'auto increment' explicitly.
Or you can write your own java code to track the Id for each table and whenever you ask the method to give the ID it will return lastID + 1.
But, I think now you can go with auto_increment option.
If you want it to autoincrement you need to say so in the column definition, and you haven't.
I don't know what 'default 1' in your title is supposed to mean, as you haven't mentioned it in your question, but you can't have a default value and autoincrement. It doesn't make sense.
I don't know what 'store seed 1' means either, in your edit.
When you have a column with a default value you want to rely on, or autoincrement, you don't mention it at all in the INSERT statement, so there is no positional argument to set.
First, set the primary identifier column to autoincrement. Since your query already excludes the primary key, you then only have to change the PreparedStatement indexes to match the number of parameters in your query starting from one.
Since you have 10 columns in addition to the primary ID column, your PreparedStatement might look something like the following:
PreparedStatement myStatement = myDBConnection.prepareStatement(myQuery);
myStatement.setString(1, studentId);
myStatement.setString(2, lastName);
myStatement.setString(3, firstName);
myStatement.setString(4, middleName);
myStatement.setString(5, placeOfBirth);
myStatement.setString(6, dateOfBirth);
myStatement.setString(7, gender);
myStatement.setString(8, civilStatus);
myStatement.setString(9, religion);
myStatement.setString(10, nationality);
Note that you do not need to have the instruction, myStatement.setInt(1, primaryId);, once you have changed the primary key in your table to auto-increment. However, if you elect to keep the primary key as non-autoincrementing, then you must explicitly specify the primary key value and provide a parameter in your query to insert that data.
If you're using MySQL Workbench, which if you're not, I highly recommend because it just works. You have to choose Auto-Increment as a characteristic of that column. If you want your column to auto increment, when creating columns in your database, check the option Auto-Increment, sometimes written as AI.
Related
String accountQuery = "insert into Account (accountNumber,currentBalance,type,personId) values (?,?,?,?);";
PreparedStatement accountPs = null;
try {
// These are my prepare Statements for my queries
accountPs = conn.prepareStatement(accountQuery);
// accountPs.setInt(1, personId.getPersonId());
accountPs.setInt(1, accountHolder.getAccountNumber());
accountPs.setDouble(2, accountHolder.getCurrentBalance());
accountPs.setString(3, accountHolder.getType());
accountPs.setInt(4, personId.getPersonId());
accountPs.executeUpdate();
accountPs.close();
conn.close();
}
How can I check if accountNumber (non primary key) already exists in my database? Whenever I run my program more than once, it'll populate my tables with repeated data because accountNumber isn't a primary key and because my accountId is an auto_increment. Note I cannot change any of the contents of the table.
create table Account(
accountId int primary key not null auto_increment,
accountNumber int not null,
currentBalance double not null,
type varchar(1) not null,
personId int not null,
foreign key(personId) references Person(personId)
);
If I understand your question, the simplest thing I can think of is to add a unique constraint to your table for account_number. Like,
ALTER TABLE Account ADD CONSTRAINT account_number_uniq UNIQUE (accountNumber)
If you want to avoid an exception, you need to check if this number is already here and if not add it.
Probably somehow like this:
String accountQuery = "insert into Account (accountNumber,currentBalance,type,personId) values (?,?,?,?);";
PreparedStatement accountPs = null;
String checkQuery = "select count(*) noAccounts from Account where accountNumber = ?";
PreparedStatement accountCheck = null;
ResultSet checker = null;
try {
accountCheck = conn.prepareStatement(checkQuery);
accountCheck.setInt(1,accountHolder.getAccountNumber());
checker = accountCheck.executeQuery();
checker.next();
if ( checker.getInt(1) == 0 ) {
// These are my prepare Statements for my queries
accountPs = conn.prepareStatement(accountQuery);
accountPs.setInt(1, accountHolder.getAccountNumber());
accountPs.setDouble(2, accountHolder.getCurrentBalance());
accountPs.setString(3, accountHolder.getType());
accountPs.setInt(4, personId.getPersonId());
accountPs.executeUpdate();
}
checker.close();
accountCheck.close();
accountPs.close();
conn.close();
}
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 want to insert values into my table only when values don't exist in the table.
String CREATETABLE = "CREATE TABLE contacts ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT, "+
"phone TEXT )";
Here is my code to create the table, I used UNIQUE(phone), and it doesn't work.
And to add a new contact I am using this code:
ContentValues values = new ContentValues();
values.put("name", contact.getName()); // get title
values.put("phone", contact.getNumero()); // get author
// 3. insert
db.insert("contacts", // table
null, //nullColumnHack
values);
I don't think there is a way of doing that without retrieving the row first. You query the database looking for that particular contact (which you have to specify at least one column to be unique, or any combination of columns to be primary key) otherwise how would you handle two person with the same name?.
So you query and search for the desired person, if you find it, check if the column is null and a) insert if it is, b) ignore if it isn't. If the query doesn't find any person, you cant just insert.
About the unique constraint, its like this:
String CREATETABLE = "CREATE TABLE contacts ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT, " +
"phone TEXT UNIQUE)";
In your sample you are using SQLiteDatabase.insert(), try to use SQLiteDatabase.insertWithOnConflict() with one of values CONFLICT_IGNORE, CONFLICT_REPLACE or others.
Also have a look about implementing database as ContentProvider which is much harder to understand but really good to know.
I have a table containing four columns:
CREATE TABLE `participants` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(128) NOT NULL,
`function` VARCHAR(255) NOT NULL,
`contact` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_function_contact` (`name`, `function`, `contact`)
)
From the application I get participants-objects, which might have values for name, functionand contactwhich are already in that exact matter in the database. In this case I want Hibernate to get me the idof that object, otherwise I want to save the object.
Using saveOrUpdate()I just get an:
org.hibernate.exception.ConstraintViolationException: Duplicate entry 'NAME-FUNCTION-CONTACT: NAME' for key 'name_function_contact'
How can I accomplish this? Thanks a lot!
Since the answers suggested that Hibernate cannot do it on its own (bummer!) I solved it the "native sql" way:
Participants tempParti = ((Participants) session.createQuery("FROM Participants WHERE name = '" + p.getName() + "' AND function = '" + p.getFunction() + "' AND contact = '" + p.getContact() + "'").uniqueResult());
if (tempParti != null) {
p = tempParti;
} else {
session.save(p);
}
Works like a charm! Thanks to all of you!
I am no expert in Hibernate. But from Mysql perspective, you do the following.
use INSERT IGNORE INTO... to add the value in the table. If the number of rows inserted is 0, then you can manually get the ID of the row by a SELECT statement.
EDIT: LAST_INSERT_ID() was wrong here. I have edited the answer.
Oracle keeps giving me an invalid identifier error when I clearly have identified the variable.
//get parameters from the request
String custID=request.getParameter("cust_ID");
String saleID=request.getParameter("sale_ID");
String firstName=request.getParameter("first_Name");
String mInitial=request.getParameter("mI");
String lastName=request.getParameter("last_Name");
String streetName=request.getParameter("street");
String city=request.getParameter("city");
String state=request.getParameter("state");
String zipCode=request.getParameter("zip_Code");
String DOB2=request.getParameter("DOB");
String agentID=request.getParameter("agent_ID");
String homePhone=request.getParameter("home_Phone");
String cellPhone=request.getParameter("cell_Phone");
String profession=request.getParameter("profession");
String employer=request.getParameter("employer");
String referrer=request.getParameter("referrer");
query =
"UPDATE customer"
+ " SET customer.cust_ID=custID, customer.sale_ID=saleID, customer.first_Name=firstName, customer.mI=mInitial, customer.last_Name=lastName, customer.street_Name=streetName, customer.city=city, customer.state=state, customer.zip_Code=zipCode,customer. DOB=DOB2, customer.agent_ID=agentID, customer.home_Phone=homePhone, customer.cell_Phone=cellPhone, customer.profession=profession, customer.employer=employer, customer.referrer=referrer"
+ " WHERE customer.cust_ID=custID " ;
preparedStatement = conn.prepareStatement(query);
preparedStatement.executeUpdate();
SQL TABLE
CREATE TABLE customer
(cust_ID NUMBER NOT NULL,
sale_ID NUMBER NOT NULL,
first_NameVARCHAR2(30) NOT NULL,
mI VARCHAR2(2) ,
last_Name VARCHAR2(50) NOT NULL,
street_Name VARCHAR2(50) ,
city VARCHAR2(30) NOT NULL,
state VARCHAR2(50) NOT NULL,
zip_Code VARCHAR2(5) NOT NULL,
DOB DATE ,
agent_ID NUMBER ,
home_Phone VARCHAR2(12) UNIQUE,
cell_Phone VARCHAR2(12) UNIQUE,
profession VARCHAR2(30) ,
employer VARCHAR2(30) ,
referrer VARCHAR2(30)
);
Your code is not doing what you think it is. Look at this:
query =
"UPDATE customer"
+ " SET customer.cust_ID=custID, customer.sale_ID=saleID, customer.first_Name=firstName, customer.mI=mInitial, customer.last_Name=lastName, customer.street_Name=streetName, customer.city=city, customer.state=state, customer.zip_Code=zipCode,customer. DOB=DOB2, customer.agent_ID=agentID, customer.home_Phone=homePhone, customer.cell_Phone=cellPhone, customer.profession=profession, customer.employer=employer, customer.referrer=referrer"
+ " WHERE customer.cust_ID=custID "
The content of query at this point is exactly what will be sent to the database. JSP will not magically fill in custID, saleID (etc...) for you before sending the query to the database. Because of this, Oracle has no sweet clue what custID is (it certainly isn't the name of some other column in the customer table). Hence, you receive the invalid identifier error.
I think you were trying to do this:
query =
"UPDATE customer"
+ " SET customer.cust_ID=" + custID + ", customer.sale_ID=" + saleID + ...
Like duffymo mentioned, this is asking for serious SQL-injection trouble (just think of the values that the client could submit in order to hijack your SQL via the custID field). The better way is to use parameters on a PreparedStatement:
query =
"UPDATE customer"
+ " SET customer.cust_ID=?, customer.sale_ID=? ...";
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, custID);
statement.setString(2, saleID);
statement.executeUpdate();
I'd recommend not using scriplets in your JSPs. Learn JSTL as quickly as you can.
The answer seems pretty obvious: your parameters are all Strings, but the Oracle schema has some Data and Number types. You've got to convert to the correct type when you INSERT.
This code is begging for a SQL injection attack. You don't do any binding or validation before you INSERT. You couldn't possibly be less secure than this. I hope you don't intend to use this site for anything on the web.
A better approach would take the scriptlet code out of the JSP, use only JSTL to write it, and introduce a servlet and some other layers to help with binding, validation, security, etc.
I think in the sql query you have entered space in between customer,DOB.
customer. DOB=DOB2