Problem in inserting data into Oracle database using JDBC - java

I am trying to insert data using prepared statement in oracle 10g database but I am getting "SQL Exception:General Error" while executing the code given below. I think the problem is either with the DATE field or PASSWORD field data retrieval. Please Help me through this. Thanks.
Student Table:-
Sid VARCHAR2(200) PRIMARY KEY CHECK(Sid>0),
Pass_word VARCHAR2(10) NOT NULL,
S_name VARCHAR2(20) NOT NULL,
G_name VARCHAR2(20) ,
Branch VARCHAR2(10) NOT NULL,
D_company VARCHAR2(20) ,
B_Percent INT NOT NULL CHECK(B_Percent<100),
twelth_percent INT NOT NULL CHECK(twelth_percent<100),
tenth_percent INT NOT NULL CHECK(tenth_percent<100),
Certify VARCHAR2(30),
Semester INT NOT NULL CHECK(Semester<9),
D_Birth DATE NOT NULL,
Sex VARCHAR2(6) NOT NULL
Code:-
int bpercent ;
int twelthpercent;
int tenthpercent;
int semester;
String studentID = null;
String studentpassword = null;
String studentname = null;
String Gname = null;
String branch = null;
String dcompany = null;
String certify = null;
String sex = null;
Date date = new Date(00-00-0000);
Connection connection = null;
try
{
// Load the JDBC driver
String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driverName);
connection = DriverManager.getConnection("jdbc:odbc:placement","siddharth","sid");
studentID = StudentID.getText();
spassword = PasswordField.getPassword();
studentname = NameField.getText();
Gname = GuardianField.getText();
branch = BranchField.getText();
dcompany = DcompanyField.getText();
bpercent = Integer.parseInt(BtechField1.getText());
twelthpercent = Integer.parseInt(TwelthField.getText());
tenthpercent = Integer.parseInt(TenthField.getText());
semester =Integer.parseInt(SemesterField.getText());
certify = CertificationField.getText();
date = (Date) DateTextField.getValue();
sex = SexCombo.getActionCommand();
PreparedStatement state = connection.prepareStatement("insert into student " +"(sid,pass_word,s_name,g_name,branch,d_company,b_percent,twelth_percent,tenth_percent,certify,semester,d_birth,sex)"+
"values(?,?,?,?,?,?,?,?,?,?,?,?,?)");
state.setString(1, studentID);
state.setString(2, spassword.toString());
state.setString(3,studentname);
state.setString(4,Gname);
state.setString(5,branch);
state.setString(6,dcompany);
state.setInt(7,bpercent);
state.setInt(8,twelthpercent);
state.setInt(9,tenthpercent);
state.setInt(10,semester);
state.setString(11,certify);
state.setDate(1, new java.sql.Date(date.getTime()));
state.setString(12,sex);
state.executeUpdate();
state.close();
JOptionPane.showMessageDialog(null,"Data Inserted","Information Messgage",JOptionPane.INFORMATION_MESSAGE);
connection.close();
}
catch (ClassNotFoundException e) {
// Could not find the database driver
JOptionPane.showMessageDialog(null,e);
}
catch (SQLException e) {
// Could not connect to the database
JOptionPane.showMessageDialog(null,e);
}
}

I believe you have a typo, you have:
state.setDate(1, new java.sql.Date(date.getTime()));
state.setString(12,sex);
And I think you want:
state.setDate(12, new java.sql.Date(date.getTime()));
state.setString(13,sex);

You've got certify and semester the wrong way round
In your insert sql string:
insert into (... tenth_percent,certify,semester,d_birth, ...)
in your
state.setInt(9,tenthpercent);
state.setInt(10,semester);
state.setString(11,certify);
state.setDate(12, new java.sql.Date(date.getTime()));
so it tries to set the semester column to a string, which is invalid.

Instead of using the lines:
`String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driverName);`
Use the line:
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver);
Sometimes, the class cannot be read by the drivermanager, so you need to register the driver with the drivermanager.
Best of Luck!
Well! there was a mistake in the code...
Instead:
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver);
Use:
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());

Related

How to check database for duplicates before inserting?

I would like to check the database for duplicates before inserting into the database. It is only considered a duplicate when plateNo, driverID and resDate match.
Here is how I get the data that will be inserted to the database
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String client = (String) clientCmb.getSelectedItem();
String[] cparts = client.split("-");
String cpart = cparts[0];
String driver = (String) driverCmb.getSelectedItem();
String[] dparts = driver.split("-");
String dpart = dparts[0];
String van = (String) vanCmb.getSelectedItem();
java.util.Date oDate = jXDatePicker2.getDate();
DateFormat oDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = oDateFormat.format(oDate);
model2.addRow(cpart, dpart, van, date);
}
And here's the code for my addRow method
public void addRow(String client, String driver, String van, String res){
try {
String sqlRes = "Select * from reservation";
rs = st.executeQuery(sqlRes);
rs.moveToInsertRow();
rs.updateString("clientID", client);
rs.updateString("plateNo", van);
rs.updateString("driverID", driver);
rs.updateString("resDate", res);
rs.insertRow();
rs.moveToCurrentRow();
rs = st.executeQuery(sqlRes);
this.fireTableDataChanged();
} catch (SQLException ex) {
Logger.getLogger(MyModel2.class.getName()).log(Level.SEVERE, null, ex);
}
Let the database do the work for you. Define a unique index/constraint specifying that those three values are unique in the table:
create unique index unq_reservation_3 on reservation(plateNo, driverID, resDate);
If you attempt to insert a duplicate -- or do an update that results in a duplicate -- then the database will return an error. You simply need to catch the error.
Use MERGE statement: T-SQL or ORACLE, or for MySQL:
PreparedStatement p = con.prepareStatement("
INSERT INTO reservation tgt (clientID, plateNo, driverID, resDate)
SELECT (? As clientID, ? As plateNo, ? As driverID, ? As resDate)
FROM DUAL ins
LEFT JOIN reservation ref
ON ref.resDate = ins.resDate
AND (ref.plateNo = ins.plateNo OR ref.driverID = ins.driverID)
WHERE ref.clientID IS NULL;
");
p.setString(1, client);
p.setString(2, van);
p.setString(3, driver);
p.setString(4, res);
return p.executeUpdate(); /* 1 - Success | 0 - Ignored Duplicate */

Java JDBC query not accepted

Hey I'm making a little webapp and have a java file in it with a function what connects a db and fetches the data.
But I'm getting a exception anyone knows why because my query is valid if I'm right.
I use eclipse and mysql workbench.
Function:
import java.sql.*;
public class Functions {
public void dbConn(String nVal, String inpVal){
System.out.println("Running function...");
if(nVal != null || inpVal != null){
String sqlSerch;
if(nVal.equals("name")){
sqlSerch = "ID, aNaam FROM profiles WHERE naam = 'casper'";
}else{
sqlSerch = "naam, aNaam FROM profiles WHERE ID = " + inpVal;
}
//driver / db path
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/profile";
//DB user&password
final String USER = "root";
final String PASS = "";
//declare con & sql var
Connection conn = null;
Statement stmt = null;
//register jdbc driver
try{
Class.forName(JDBC_DRIVER);
//make a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//SQL Statement
stmt = conn.createStatement();
String sql = "SELECT "+ sqlSerch;
ResultSet rs = stmt.executeQuery(sql);
//Declareer variablen met data uit db
//int id = rs.getInt("ID");
String naam = rs.getString("naam");
String aNaam = rs.getString("aNaam");
System.out.println( naam + aNaam);
rs.close();
stmt.close();
conn.close();
}catch(Exception e){
System.out.println(e);
}
System.out.println(" - " + nVal + " - " + inpVal);
}
}
}
exception:
java.sql.SQLException: Column 'naam' not found.
database structure:
Thank you in advance,
Casper
When you receive "name" through the nVal parameter, you select only ID and aNaam columns.
So, if you try to get values for naam from that ResultSet you get the Exception.
Also, I suggest limiting the results of your query to 1, since you use the WHERE clause with naam and ID, which seem to be not unique, unless there's some constraint not included in the screenshot.
Hope this helped.
You branch and create your queries:
if(nVal.equals("name")){
sqlSerch = "ID, aNaam FROM profiles WHERE naam = 'casper'";
}else{
sqlSerch = "naam, aNaam FROM profiles WHERE ID = " + inpVal;
}
Then regardless of the branch, you get your result set values:
String naam = rs.getString("naam");
String aNaam = rs.getString("aNaam");
But "naam" will not be in your "ID, aNaam" search.
In general, a good rule of thumb is to always return the same columns.

error in inserting data to database

Here's my code for createFood DA so that can insert to database. However , there is a nullPointerException at
pstmt.setString(2, food.getFoodName());
public static int createFood(Food food) {
// declare local variables
int orderID ;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - establish connection to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "INSERT INTO orderitems (orderId, foodName, foodPrice, quantity,) VALUES(?,?,?,? )";
pstmt = (PreparedStatement) db.getPreparedStatement(dbQuery);
orderID = getNextOrderId();
// step 3 - to insert record using executeUpdate method
try {
pstmt.setInt(1,orderID );
pstmt.setString(2, food.getFoodName());
pstmt.setDouble(3 ,food.getFoodPrice());
pstmt.setInt(4, food.getQuantity());
if (pstmt.executeUpdate() == 1)
return orderID;
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return -1;
}
This is the code when i click on "orders".
private void actionPerformedOrder() {
//retrieve user input
String numPax = (String) cbNoPax.getSelectedItem();
String tableNo= (String)cb_tableno.getSelectedItem();
java.util.Date utilDate = new java.util.Date();
Date orderDate = new Date(utilDate.getTime());
System.out.println("Date " + orderDate);
orders = new Orders(Integer.parseInt(tableNo),Integer.parseInt(numPax), (java.sql.Date) orderDate, totalAmount);
int orderID = OrdersDA.createOrders(orders);
OrderItems od;
for (Food fd: foodList) {
od = new OrderItems(orderID, fd.getFoodName(), fd.getQuantity(), fd.getFoodPrice());
FoodDA.createFood(food);
}
I still cannot figure out the error. Anyone knows where went wrong ? Much help will be appreciated.
You have passed createFood() method food variable which i cant see declare anywhere
try
createFood(fd) according to your code.

How to call parameterized stored procedure in jdbc

I need to call a parameterized stored procedure in java jdbc from sql server.
The stored procedure goes like this in sql
create proc patientreg
#id int
as
begin
select [patient_id],[Psurname], [pFirstname], [pMiddlename], [reg_date], [DOB], [Sex], [Phone_num], [Addr],[Email],[dbo].[fncomputeage](DOB) from [dbo].[Patient_registration] where [patient_id] = #id
end
please note dbo.fncompute(DOB) is a function
To call it in JDBC:
try{
String str = "{call patientreg(?)}";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbcdbc:GeneralHospital");
cstmt = con.prepareCall(str);
cstmt.setInt(1, Integer.parseInt(t.getText()));
cstmt.execute();
int pid = cstmt.getInt(1);
String sname = cstmt.getString(2);
String fname = cstmt.getString(3);
String mname = cstmt.getString(4);
String regdate = cstmt.getString(5);
String dob = cstmt.getString(6);
String sex = cstmt.getString(7);
String phonenum = cstmt.getString(8);
String address = cstmt.getString(9);
String email = cstmt.getString(10);
int age = cstmt.getInt(11);
l1.setText(sname+""+ fname+""+mname);
l3.setText(Integer.toString(pid));
l4.setText(regdate);
l5.setText(dob);
l6.setText(Integer.toString(age));
l7.setText(sex);
l8.setText(phonenum);
l9.setText(address);
l10.setText(email);
cstmt.close();
}
catch(Exception ex)
{
System.out.println("Error occured");
System.out.println("Error:"+ex);
}
After doing it this way it throwing an exception:
Error:java.sql.SQLException: Parameter 1 is not an OUTPUT parameter
there is a couple of problems with your code.
First, Don't use the jdbc odbc driver! It is unstable, and might not work correctly. Use Microsoft's own jdbc driver, or, even better, use jTDS, which is an excellent open source jdbc driver for Sql Server.
Second, the getInt, getString etc methods on CallableStatement is used to retrieve output parameters from the stored procedure. What you have is an ordinary resultset.
CallableStatement cstmt = con.prepareCall("{call patientreg(?)}");
// add input parameter
cstmt.setInt(1, someInteger);
// execute and get resultset.
ResultSet rs = cstmt.executeQuery();
// read resultset
while (rs.next()) {
int pid = rs.getInt(1);
String sname = rs.getString(2);
String fname = rs.getString(3);
// etc.
}
// remember to close statement and connection
try this
ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?");
cs.setString(1, "val1");
cs.setString(2, "val2");
rs = cs.executeQuery();
ArrayList<YourClass> listYourClass = new ArrayList<YourClass>();
while (rs.next()) {
YourClassret= new YourClass();
ret.set1(rs.getString(1));
ret.set2(rs.getString(2));
ret.set3(rs.getString(3));
listaObjectX.add(ret);
}
return listYourClass ;
} catch (SQLException se) {
System.out.println("Error "+ se.getMessage());
se.printStackTrace();
} finally {
try {
rs.close();
cs.close();
con.close();
} catch (SQLException ex) {
//do ex.print
}
}

How to change the database name and table using java?

i try to understand this part of code:
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("mysqlpassword");
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st = conn.prepareStatement("insert into 'Email_list' values(?)");
for(String mail:mails)
i understand that test database is a default database. but if i want to use an existing database, i will just modify test to another database name isn't it?
If yes how do i modify my code if my new database is Test2 with table name Email which contains mail column with varchar(100)
i try to replace test by Test2 Email_list by Email but i don't know where to put the column name mail.
Thank you for help
The INSERT statement you use omits the columns.
INSERT INTO tablename VALUES (1, 2, 3)
can be written if the table has three columns and for all three columns values are provided.
If some columns can be left empty or have default values, you can write
INSERT INTO tablename (column1, column2) VALUES (1, 2)
In this cas the value for column3 is null or the default value.
So in your case the column name is put nowhere.
You are missing PORT number in your connection string...
String url = "jdbc:mysql://localhost/test"; should be String url = "jdbc:mysql://localhost:PORT_NUMBER/test"; like String url = "jdbc:mysql://localhost:3306/test";
Let me know if you have any queries...
Also, Check below how Prepared Statement works
import java.sql.*;
public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Good Luck!!!

Categories

Resources