ORA-00913: too many values - java

getting ORA-00913: too many values. don't know how to resolve this issue please anyone could help me?
con2 = DriverManager.getConnection("Jdbc:Oracle:thin:#localhost:1521:XE", "system",
"oracle123");
File image=new File("E:/Users/ganesh/Desktop/line.jpg");
String sql="insert into blobtab values(?,?)";
pstmt=con2.prepareStatement(sql);
pstmt.setString(1,"akshita");
fis=new FileInputStream(image);
pstmt.setBinaryStream(2,(InputStream)fis,(int)(image.length()));
int s = pstmt.executeUpdate();
if (s > 0) {
System.out.println("Image Uploaded successfully !");
} else {
System.out.println("unsucessfull to upload image.");
}
con2.close();
pstmt.close();

This would suggest that your blobtab table didn't have two columns in it (or if there's a trigger on the table, check the DML being fired recursively in those for the same problem).
insert into blobtab values(?,?)
eg:
SQL> create table foo(id number);
Table created.
SQL> insert into foo values (1, 2);
insert into foo values (1, 2)
*
ERROR at line 1:
ORA-00913: too many values
check your table. also you should always put explicit column names on your insert (in case someone adds default or nullable columns later on. i.e. always do:
insert into blobtab (col1, col2) values(?,?)
where col1 col2 are your real column names.

the number of column would have been less than the paraemeter/argument passed
eg: insert into insert into foo(name , age) values (?,?,?) and then preparedStatment object insert
Since there is 2 column and value have 3 parameter
therefore ,
ORA-00913: too many values

Related

How to automatically insert date and time into sql table

I've created a table name EventLog7 in SQL Server 2008 :
create table EventLog7(
EventId int not null identity(1,1),
EventDate datetimeconstraint DF_myDate DEFAULT (getdate()),
ObjectId varchar(50),
Name varchar(50),
Value varchar (50)
)
In NetBeans, there are three jtextfields which help to insert data into EventLog SQL Table (ObjectId, Name, Value) when I press the button.
Mentioned below action button code:
String objectid=jTextField1.getText();
String value=jTextField2.getText();
String name=jTextField3.getText();
try{
DoConnect();
st=conn.createStatement();
String sql = "insert into EventLog7 values('"+objectid+"','"+name+"','"+value+"')";
pst = conn.prepareStatement(sql);
pst.execute();
rs=st.executeQuery("select * from EventLog7");
jTable1.setModel(net.proteanit.sql.DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
So, i want that when I insert values of ObjectId,Name,Value in three jtextfiles then Sql table will insert automatically date and time with these data.
But according to my code, it's showing error
Column names or number of supplied values does not match table definition
So please provide me right way.
String sql = "insert into EventLog7 values('"+objectid+"','"+name+"','"+value+"')";
line will be
String sql = "insert into EventLog7(ObjectId, Name, Value, EventDate) values('"+objectid+"','"+name+"','"+value+"',GETDATE())";
I do not know how the IDs is generated sql-server , you may need to set it as well if that is not auto assign/increment.
And I can say this is not secure, you need to use ?s instead of your variables and use set methods to set them as a_horse_with_no_name reminds. Use what I suggested only for mitigating the error you have now.

Insert,Update,Retrive using stored procedures or functions in mysql

Check whether the primary key exists in the table.
If exists retrieve three column values and update the three column values with new values.
String sql = "SELECT brno, brdate, type1,type,flag,mcode,pamount,tax,pamount1,liab FROM rawdata WHERE mcode="+mcode;
ResultSet rs = statement.executeQuery(sql);
rs.first();
float oldPamount= rs.getFloat("pamount");
float tax= rs.getFloat("tax");
float oldPamount1= rs.getFloat("pamount1");
float newPamount= pamount;
float newTax= tax;
float newPamount1= pamount1;
rs.updateFloat("pamount", newPamount);
rs.updateFloat("tax", newTax);
rs.updateFloat("pamount1", newPamount1);
rs.updateRow();
If not exists insert the record and retrieve it.
I have tried this:
INSERT INTO rawdata (brno, brdate, type1,type,flag,mcode,pamount,tax,pamount1,liab)
SELECT * FROM (SELECT '1', '02.05.15', 'G','H','E','2222','789.00','0.00','789.00','L') AS tmp
WHERE NOT EXISTS (
SELECT mcode FROM rawdata WHERE mcode = '2222'
);
But it getting the following error duplicate value 789.00
I need to done these things at a time not separate queries.
This is my table(rawdata) with fields(brno, brdate, type1,type,flag,mcode,pamount,tax,pamount1,liab) where mcode is the primarykey
Here the pamount,tax,pamount1 need to be updated if the record exists.
For Ex:
These are the sample values 873.00,0.00,873.00 needed to be updated to 789.00,0.00,789.00 (or) 24000.00,240.00,23760.00
Other wise need to insert entire row for the new mcode
I have tried the above queries, but i need to be done at time.

How to avoid inserting null values into Primary key or Not Null columns?

I am inserting into a table from my jdbc program,
like this
PreparedStatement ps = con.prepareStatement(sqlqry);
ps.setInt(1,dto.getInstall_id());
ps.setString(2, dto.getDashboard_name());
ps.setString(3, dto.getDashboard_type());
ps.setString(4, dto.getDashboard_image());
But in the table i have column say D_ID which in is primary key and i dont want o insert the D_ID from my program into table because the same id might be already exist. So for avoiding the PK_CONSTRAINT I am not inseting it.
But when i try this i am getting this error.
ORA-01400: cannot insert NULL into ("TESTDB"."TESTATBLE"."D_ID")
So how can i solve this problem, Any alternative like if i insert D_ID from the program my JDBC program the D_ID column should dynamically generate id's in the table.
I am banging my head for this. Please help!
You should create that ID using a sequence. So for each ID column that you have, you create a corresponding sequence:
create table testatble
(
d_id integer not null primary key,
install_id integer not null,
dashboard_name varchar(100)
... more columns ....
);
create sequence seq_testatble_d_id;
You can use it like this:
// note that there is no placeholder for the D_ID column
// the value is taken directly from the sequence
String sqlqry =
"insert into testatble (d_id, install_id, dashboard_name) " +
"values (seq_testatble_d_id.nextval, ?, ?)";
PreparedStatement ps = con.prepareStatement(sqlqry);
ps.setInt(1,dto.getInstall_id());
ps.setString(2, dto.getDashboard_name());
... more parameters ...
ps.executeUpdate();
That way the id will be generated automatically.
If you need the generated ID in your Java code after the insert, you can use getGeneratedKeys() to return it:
// the second parameter tells the driver
// that you want the generated value for the column D_ID
PreparedStatement ps = con.prepareStatement(sqlqry, new String[]{"D_ID"});
// as before
ps.setInt(1,dto.getInstall_id());
ps.setString(2, dto.getDashboard_name());
... more parameters ...
ps.executeUpdate();
// now retrieve the generated ID
int d_id = -1;
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) // important!
{
d_id = rs.getInt(1);
}
rs.close();
More on sequences in the Oracle manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/pseudocolumns002.htm#SQLRF00253
You should use Auto Increment number for ID(I Oracle you can use sequence). You can do this at the link:
Create ID with auto increment on oracle
You should also read this. If there is a sequence to your ID then here you can read information about that.

Adding data into mysql database without repeating data

I'm supposed to add data from my csv file into my database. I have no problem adding data into the database, however, I have a situation where my java program has to add new values or update current values into the database, say under my column "date". When a new data is not identified in my current database, it would be added. However, under the same row, there's a column called "demand". If the date is the same but the demand is different. It would have to be updated. At the moment, my script can only retrieve the data line by line from mysql and compare with the data collected from the csv file. When the date is different, it can add the data into a new row. The problem is that the java program that I created can only read line by line from the beginning. I would have a repetition of data because when it start comparing from the earliest data to the latest. For example, my earliest date is 01 jan and it is compared to my csv data say 31 jan. However, my later entries has a 31 jan already stored. But my java program continue to add this data in because it compared from the beginning. I will explain in greater detail if you need more information.
public void readDataBase(int val, String d1, String d2, String d3, String d4 ) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
statement = connect.createStatement();
resultSet = statement.executeQuery("SELECT COUNT(*) FROM testdb.amg");
while (resultSet.next()) {
total = resultSet.getInt(1);
}
resultSet = statement.executeQuery("select * from testdb.amg");
try{
int id;
String Date,Demand;
while (resultSet.next()) {
id = resultSet.getInt("id");
Date = resultSet.getString("Date");
Demand = resultSet.getString("Demand");
System.out.println("total: " + total);
System.out.println("d4: " + d4);
if (!Date.equals(d1) && !Demand.equals(d3))
{
int val1 = total +1;
preparedStatement = connect
.prepareStatement("insert into testdb.amg values (?, ? ?)");
preparedStatement.setInt(1, val1);
preparedStatement.setString(2, d1);
preparedStatement.setString(3, d3);
preparedStatement.executeUpdate();
System.out.println("UpdatedII");
}
Identify the distinct columns in your database (date + demand + whatever_is_distinct ) and define a UNIQUE constraint on that combination.
By doing that ,during insertion, if there is any Constraint Violation exception that gets thrown , update that record or else the record gets inserted.
As Rocky said, define the unique key on the table. Since the database is MySQL, you can achieve what you want by simple query with INSERT... ON DUPLICATE KEY UPDATE ... INSERT ... ON DUPLICATE KEY UPDATE Syntax
In your case it can be
insert into testdb.amg values (?, ? ?) on duplicate key update <update fields here>
So the final query shall be
"insert into testdb.amg values (?, ?, ?) on duplicate key update Demand=?"
and add
preparedStatement.setString(4, d3);

Why does getGeneratedKeys() return "GENERATED_KEY" as column name?

I'm playing with the JDBC/MySQL 5.1. I created an insert query to insert some data into a table and want to return the generated key from the newly created row. However, when I go to reference the column by "id" which is my PK and auto-increment column.
PreparedStatement ps = St0rm.getInstance().getDatabase("main")
.prepare("INSERT INTO quests (name,minlevel,start_npc,end_npc) VALUES(?,?,?,?)", true); // creates a prepared statement with flag RETURN_GENERATED_KEYS
// ...
int affected = ps.executeUpdate();
ResultSet keys = ps.getGeneratedKeys();
if (affected > 0 && keys.next()) {
St0rm.getInstance().getLogger().warning(String.format("ID Column Name: %s", keys.getMetaData().getColumnName(1))); // says the column name is: GENERATED_KEY
q = new Quest(keys.getInt(1)); // column index from the generated key, no error thrown.
q = new Quest(keys.getInt("id")); // actual column name, line throws a SQLException
// ...
}
So, my question: Why does ResultSet.getGeneratedKeys use GENERATED_KEY as the column name?
You shouldn't retrieve these columns by name. Only by index, since
there can only ever be one column with MySQL and auto_increments that
returns value(s) that can be exposed by Statement.getGeneratedKeys().
Currently the MySQL server doesn't return information directly that
would make the ability to retrieve these columns by name in an
efficient manner possible, which is why I'm marking this as "to be
fixed later", since we can, once the server returns the information in
a way that the driver can use.
From here (in 2006!).

Categories