Insert into Database using form in Netbeans 7.01 - java

I'm doing an individual project in java. I want to insert data into my database...but my program is successfully running without any error but when insert data and submit the my data it will give an error like this java.sql.SQLException: Can not issue data manipulation statements with executeQuery().This My Code: \
what can do for solved this problem
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == jButton1)``
{
int x = 0;
String s1 = jTextField1.getText().trim();
String s2 = jTextField2.getText();
char[] s3 = jPasswordField1.getPassword();
char[] s4 = jPasswordField2.getPassword();
String s8 = new String(s3);
String s9 = new String(s4);
String s5 = jTextField5.getText();
String s6 = jTextField6.getText();
String s7 = jTextField7.getText();
if(s8.equals(s9))
{
try{
File image = new File(filename);
FileInputStream fis = new FileInputStream(image);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
cat_image = bos.toByteArray();
PreparedStatement ps = conn.prepareStatement("insert into reg values(?,?,?,?,?,?,?)");
ps.setString(1,s1);
ps.setString(2,s2);
ps.setString(3,s8);
ps.setString(4,s5);
ps.setString(5,s6);
ps.setString(6,s7);
ps.setBytes(7,cat_image);
rs = ps.executeQuery();
if(rs.next())
{
JOptionPane.showMessageDialog(null,"Data insert Succesfully");
}else
{
JOptionPane.showMessageDialog(null,"Your Password Dosn't match" ,"Acces dinied",JOptionPane.ERROR_MESSAGE);
}
}catch(Exception e)
{
System.out.println(e);
}
}

Use ps.executeUpdate() or ps.execute().
From executeUpdate
Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as
INSERT, UPDATE or DELETE; or an SQL statement that returns nothing,
such as a DDL statement.
From execute
Executes the SQL statement in this PreparedStatement object, which
may be any kind of SQL statement. Some prepared statements return
multiple results; the execute method handles these complex statements
as well as the simpler form of statements handled by the methods
executeQuery and executeUpdate.The execute method returns a boolean to
indicate the form of the first result. You must call either the method
getResultSet or getUpdateCount to retrieve the result; you must call
getMoreResults to move to any subsequent result(s).
Then modify your code properly
int rowsAffected = ps.executeUpdate();
JOptionPane.showMessageDialog(null,"Data Rows Inserted "+ rowsAffected);
Also you have to close your streams and connections in a finally block.

SQLException is thrown because of wrong sql statement. You may have syntax error while inserting string and integer values. Check your sql statement after VALUES there should be "1-0" around integer elements and '"some value"' around string elements.

Related

Append row in Sql without replacing previous row java

So i have database with value like this...
i'm trying to append the value by using insert into without replacing it,the data from this txt file...
but when i reload/refresh the database there is no new data being appended into the database...,
here is my code....
public static void importDatabase(String fileData){
try{
File database = new File(fileData);
FileReader fileInput = new FileReader(database);
BufferedReader in = new BufferedReader(fileInput);
String line = in.readLine();
line = in.readLine();
String[] data;
while (line != null){
data = line.split(",");
int ID = Integer.parseInt(data[0]);
String Nama = data[1];
int Gaji = Integer.parseInt(data[2]);
int Absensi = Integer.parseInt(data[3]);
int cuti = Integer.parseInt(data[4]);
String Status = data[5];
String query = "insert into list_karyawan values(?,?,?,?,?,?)";
ps = getConn().prepareStatement(query);
ps.setInt(1,ID);
ps.setString(2,Nama);
ps.setInt(3,Gaji);
ps.setInt(4,Absensi);
ps.setInt(5,cuti);
ps.setString(6,Status);
line = in.readLine();
}
ps.executeUpdate();
ps.close();
con.close();
System.out.println("Database Updated");
in.close();
}catch (Exception e){
System.out.println(e);
}
}
When i run it, it shows no error but the data never get into database, where did i go wrong?.,...
Auto-commit mode is enabled by default.
The JDBC driver throws a SQLException when a commit or rollback operation is performed on a connection that has auto-commit set to true.
Symptoms of the problem can be unexpected application behavior
update the JVM configuration for the ActiveMatrix BPM node to use the following Oracle connection property:
autoCommitSpecCompliant=false Try once
Note:I am not able to put as comment so i posted as a answer

Issue with getBinaryStream(index)

I am getting null value when I am reading the blob data from database. What might be the issue? Can some one help me on this?
Connection con = null;
PreparedStatement psStmt = null;
ResultSet rs = null;
try {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con =
DriverManager.getConnection("jdbc:oracle:thin:#MyDatabase:1535:XE","password","password");
System.out.println("connection established"+con);
psStmt = con
.prepareStatement("Select Photo from Person where Firstname=?");
int i = 1;
psStmt.setLong(1, "Nani");
rs = null;
rs = psStmt.executeQuery();
InputStream inputStream = null;
while (rs.next()) {
inputStream = rs.getBinaryStream(1);
//Blob blob = rs.getBlob(1);
//Blob blob1 = (Blob)rs.getObject(1);
//System.out.println("blob length "+blob1);//rs.getString(1);
}
System.out.println("bytessssssss "+inputStream);//here i am getting null value.
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I believe you didn't use setString function to assign any value to firstname which leads to null
for example:
ps.preparedStatement("Select photo from person where firstname = ?");
ps.setString(1,"kick"); <----- add this line
system.out.println("bytes "+rs.getBinaryStream(1));
Another suggestions
there is no need to use rs = null; inside try catch block because you have rs=null; at beginning of
your code.
change
InputStream inputStream = null;
to
InputStream inputStream = new InputStream();
or
get rid of InputStream inputStream = null;
source you should take a look at
The most obvious error is using setLong instead of setString.
However one practice is fatal: declaring in advance. This in other languages is a good practice, but in java one should declare as close as possible.
This reduces scope, by which you would have found the error! Namely inputStream is called after a failed rs.next() - outside the loop. Maybe because no records were found.
This practice, declaring as near as feasible, also helps with try-with-resources which were used here to automatically close the statement and result set.
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#MyDatabase:1535:XE","password","password");
System.out.println("connection established"+con);
try (PreparedStatement psStmt = con.prepareStatement(
"Select Photo from Person where Firstname=?")) {
int i = 1;
psStmt.setString(1, "Nani");
try (ResultSet rs = psStmt.executeQuery()) {
while (rs.next()) {
try (InputStream inputStream = rs.getBinaryStream(1)) {
//Blob blob = rs.getBlob(1);
//Blob blob1 = (Blob)rs.getObject(1);
//System.out.println("blob length "+blob1);//rs.getString(1);
Files.copy(inputStream, Paths.get("C:/photo-" + i + ".jpg"));
}
++i;
}
//ERROR System.out.println("bytessssssss "+inputStream);
} // Closes rs.
} // Closes psStmt.
}
1- In your code when setting the parameter's value of SQL query, be sure to use the appropriate data type of the field. So here you should use
psStmt.setString(1, "Nani");
instead of
psStmt.setLong(1, "Nani");
2- Make sure that the query is correct (Table name, field name).
3- Make sure that the table is containing data.

Insertion of BLOB fails with the file being NULL

In Java, with JDBC I am trying to insert a file in a BLOB column in a table of an Oracle database.
Here is how I proceed:
private Statement getStatement(File f, String fid, Long dex, String uid, int id)
{
FileInputStream fis = null;
PreparedStatement statement;
try
{
statement = connection.prepareStatement("INSERT INTO BLOBTABLE (FID, FDEX, SFILE, UID, ID) VALUES (?, ?, ?, ?, ?)");
statement.setString(1, fid);
statement.setLong(2, dex);
fis = new FileInputStream(file);
statement.setBinaryStream(3, fis, file.length());
statement.setString(4, uid);
statement.setInt(5, id);
}
finally
{
if (fis != null)
fis.close();
}
return statement;
}
private insertStuff()
{
File f = new File("/home/user/thisFileExists");
PreparedStatement statement = getStatement(f, "XYZ", 18L, "ABC", 78);
statement.execute();
}
When the .execute is run, I get an Oracle error:
java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("ORACLEUSER"."BLOBTABLE"."SFILE")
SFILE is the BLOB column. So this means the database at the end of the chain receives NULL in the query.
How come?
If I replace:
statement.setBinaryStream(3, fis, file.length());
With:
statement.setBinaryStream(3, new ByteArrayInputStream(("RANDOMSTRING".getBytes())));
It works so it somehow does not like my file stream.
Is it a problem that I close the stream? that is how they do it on all samples I saw.
You're closing the FileInputStream before you execute the statement, so there's no way for the statement to get the data when it actually needs it. It would better to pass an InputStream into your method, so you can close it externally after the statement has executed:
private insertStuff() {
File file = new File("/home/user/thisFileExists");
try (InputStream stream = new FileInputStream(file)) {
PreparedStatement statement = getStatement(stream, "XYZ", 18L, "ABC", 78);
statement.execute();
}
}
... where getStatement would accept an InputStream instead of the File, and use the overload of setBinaryStream which doesn't take a data length. Alternatively, you could pass in the File and it could open the stream, create the statement, execute the statement, then close the stream.
As a side note, you should be closing the statement using a try-with-resource or try/finally statement, too.
You are closing the FileInputStream before the database has used it. The JDBC driver is allowed to defer consumption of the stream until the actual execute.
Also note that your test comparison with a fixed string isn't entirely fair: it isn't the same method overload so it might be that one works and the other one doesn't (although that isn't the case here).

How do I connect to data base from servlet. I have tried the following code, but control goes to exception everytime

How do I connect to data base from servlet. I have tried the following code, but control goes to exception everytime.
try
{
int num_rows = 0;
Connection con = null;
Statement st = null;
Statement search = null;
ResultSet rs = null;
ResultSet searchRS = null;
// Connecting to the database
PrintWriter out = response.getWriter();
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/employees","root","");
st = con.createStatement();
rs = st.executeQuery("select employees.first_name,employees.last_name,employees.gender,employees.hire_date,departments.dept_name,salaries.salary from employees,departments,salaries,dept_emp where employees.emp_no=salaries.emp_no AND dept_emp.emp_no=employees.emp_no AND dept_emp.dept_no=departments.dept_no AND salaries.to_date='9999-01-01' AND (employees.first_name='"+Sname+"' OR employees.last_name='"+Sname+"')");
//Retrieval of data from result set retrieved from database
String[][] str = new String[10][6];
while( rs.next())
{
str[num_rows][0] = rs.getString("first_name");
str[num_rows][1] = rs.getString("last_name");
str[num_rows][2] = rs.getString("gender");
str[num_rows][3] = rs.getString("hire_date");
str[num_rows][4] = rs.getString("dept_name");
str[num_rows][5] = rs.getString("salary");
num_rows++;
}
if(num_rows <10)
{
isLast = true;
var = 0;
}
request.setAttribute("listvalue",str);
request.setAttribute("rows",num_rows);
RequestDispatcher RequestDispatcherObj =request.getRequestDispatcher("SearchName.jsp");
RequestDispatcherObj.forward(request, response);
out.flush();
con.close();
var = var +10;
}
catch(Exception e)
{
e.printStackTrace();
}
Your string array can hold 10 records; probably you are getting more than that from the database.
You may try this-
while( rs.next() && num_rows < 10 )
In case you need to collect all the records, better use some collection like List.
For me looks like the line
RequestDispatcherObj.forward(request, response);
is creating the problem. It is forwarding the request to some other place. The requestdispatcheobj may have closed the out object. So after that use of flush() and write() will lead to an IllegalStateException.
out.flush();
con.close();
var = var +10;
So make sure this is not the case.

Performance Tuning While Loading CSV

I have attached below code
Functionality
Reading csv and insert in db after replacing values with webmacro.
Reading values from csv # first header information NO,NAME next to that read one by one values and put into webmacro context context.put("1","RAJARAJAN") next webmacro replace $(NO) ==>1 and $(NAME)==>RAJARAJAN and add in statment batch once it reached 1000 execute the batch.
Code is running as per functionality but it takes 4 minutes to parse 50,000 records need performance improvement or need to change logic ....kindly let me know if any doubts.
Any change to drastic performance...
Note: I use webmacro because to replace $(NO) in merge query to values read in CSV
Bala.csv
NO?NAME
1?RAJARAJAN
2?ARUN
3?ARUNKUMAR
Connection con=null;
Statement stmt=null;
Connection con1=null;
int counter=0;
try{
WebMacro wm = new WM();
Context context = wm.getContext();
String strFilePath = "/home/vbalamurugan/3A/email-1822820895/Bala.csv";
String msg="merge into temp2 A using
(select '$(NO)' NO,'$(NAME)' NAME from dual)B on(A.NO=B.NO)
when not matched then insert (NO,NAME)
values(B.NO,B.NAME) when matched then
update set A.NAME='Attai' where A.NO='$(NO)'";
String[]rowsAsTokens;
con=getOracleConnection("localhost","raymedi_hq","raymedi_hq","XE");
con.setAutoCommit(false);
stmt=con.createStatement();
File file = new File(strFilePath);
Scanner scanner = new Scanner(file);
try {
String headerField;
String header[];
headerField=scanner.nextLine();
header=headerField.split("\\?");
long start=System.currentTimeMillis();
while(scanner.hasNext()) {
String scan[]=scanner.nextLine().split("\\?");
for(int i=0;i<scan.length;i++){
context.put(header[i],scan[i]);
}
if(context.size()>0){
String m=replacingWebMacroStatement(msg,wm,context);
if(counter>1000){
stmt.executeBatch();
stmt.clearBatch();
counter=0;
}else{
stmt.addBatch(m);
counter++;
}
}
}
long b=System.currentTimeMillis()-start;
System.out.println("=======Total Time Taken"+b);
}catch(Exception e){
e.printStackTrace();
}
finally {
scanner.close();
}
stmt.executeBatch();
stmt.clearBatch();
stmt.close();
}catch(Exception e){
e.printStackTrace();
con.rollback();
}finally{
con.commit();
}
// Method For replace webmacro with $
public static String replacingWebMacroStatement(String Query, WebMacro wm,Context context) throws Exception {
Template template = new StringTemplate(wm.getBroker(), Query);
template.parse();
String macro_replaced = template.evaluateAsString(context);
return macro_replaced;
}
// for getting oracle connection
public static Connection getOracleConnection(String IPaddress,String username,String password,String Tns)throws SQLException{
Connection connection = null;
try{
String baseconnectionurl ="jdbc:oracle:thin:#"+IPaddress+":1521:"+Tns;
String driver = "oracle.jdbc.driver.OracleDriver";
String user = username;
String pass = password;
Class.forName(driver);
connection=DriverManager.getConnection(baseconnectionurl,user,pass);
}catch(Exception e){
e.printStackTrace();
}
return connection;
}
I can tell you that this code takes on average about 150ms on my machine:
StrTokenizer tokenizer = StrTokenizer.getCSVInstance();
for (int i=0;i<50000;i++) {
tokenizer.reset("a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z");
String toks[] = tokenizer.getTokenArray();
}
You'll find StrTokenizer in the apache commons-lang package, but I would doubt that String.split(), StringTokenizer or Scanner.nextLine() would be your bottleneck in any case. I would assume it's your database inserts times.
If that's the case you can do 1 of two things:
Tune your batch size.
Multithread the inserts
And as suggested, a profiler will help to determine where your time is spent.,

Categories

Resources