jdbc中的preparedstatement和execute方法的问题 [英] Problem with preparedstatement and execute method in jdbc

查看:113
本文介绍了jdbc中的preparedstatement和execute方法的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

package sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ConnectionDemo {
	
	 public static void main(String[] args) {
	
		 try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			 Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","9848451415");
			 PreparedStatement st = con.prepareStatement("insert into emp(empno,ename) values(?,?)");
			 st.setInt(1, 3);
			 st.setString(2, "Naresh");
			 if(st.execute()){
				 System.out.println("Successfull executed");
			 }
			 else
				 System.out.println("Failed");
			
			 
		 }	 
		 catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 
		 
	 } 
}





我尝试了什么:



我试图在现有的表emp中插入另一条记录。最初执行程序但我的本地数据库没有更新。



What I have tried:

I tried to insert another record into the existing table emp. Initially program is executed but my local database didnt got updated.

推荐答案

我个人会使用st.executeUpdate()返回一个整数。如果整数值大于0,则语句已成功执行,否则它将为0或抛出将在catch块中捕获的错误。

另一个问题是数据库连接。你确定你的连接不是空的吗?您是否还将ojdbc jar文件/库加载到类路径中?请检查二并更新我们。



if(st.execute()){

System.out.println(成功执行);

}



将更改为if(st.executeUpdate()> 0){

System.out.println(成功执行);

}
I would personally use st.executeUpdate() which returns an integer. If the integer value is greater than 0, the statement has been executed successfully otherwise it will either be 0 or throw an error which will be caught in the catch block.
Another issue would be in database connection. Have you ensured that your connection is not null? Have you also loaded ojdbc jar file/ library to your classpath? Kindly check on the two and update us.

if(st.execute()){
System.out.println("Successfull executed");
}

would change to if(st.executeUpdate()>0){
System.out.println("Successfull executed");
}


根据我的观点,你应该在ps initialziation之后写ps.executeUpdate()
According 2 my point of view, u should write ps.executeUpdate() after ps initialziation


这篇关于jdbc中的preparedstatement和execute方法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆