JDBC语句接口
时间:2020-01-09 10:35:20 来源:igfitidea点击:
java.sql.Statement用于执行静态SQL语句并返回其产生的结果。语句接口具有两个子接口
- PreparedStatement –存储预编译的SQL语句,然后可以通过传递不同的参数值来多次执行该语句。在此后JDBC PreparedStatement接口中阅读有关PreparedStatement的更多信息。
- CallableStatement –用于执行SQL存储过程。在此后JDBC CallableStatement接口中阅读有关CallableStatement的更多信息。
Statement界面中的方法
此处详细介绍了一些Statement接口的常用方法
- execute(String sql)–执行给定的SQL语句,该语句可能返回多个结果。该方法返回一个布尔值;如果第一个结果是ResultSet对象,则为true;否则为false。如果是更新计数或者没有结果,则返回false。
- executeQuery(String sql)–执行给定的SQL语句,返回一个ResultSet对象。适用于运行SELECT查询。
- executeUpdate(String sql)–执行指定的SQL,它可以是INSERT,UPDATE或者DELETE语句或者不返回任何内容的SQL语句,例如SQL DDL语句(Create,Drop)。
- addBatch(String sql)-如果要批量运行一堆SQL语句,则此方法会将给定的SQL命令添加到此Statement对象的当前命令列表中。
- executeBatch()–将一批命令提交到数据库以执行。
- close()–立即释放此Statement对象的数据库和JDBC资源。
Java中的语句示例
在示例中,我们将使用三种类型的execute方法,execute(),executeQuery()和executeUpdate()来更好地了解如何使用这些方法。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCStatementDemo {
public static void main(String[] args) {
Connection connection = null;
try {
// Load driver
Class.forName("com.mysql.cj.jdbc.Driver");
// connection object
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/theitroad",
"root", "admin");
// create Statement object
Statement statement = connection.createStatement();
/** execute method **/
boolean flag = statement.execute("UPDATE Employee SET DEPARTMENT = 'HR' where id = 15");
// flag false means not returning resultset
if(flag == false){
System.out.println("Updated rows " + statement.getUpdateCount() );
}
/** executeUpdate method **/
// Insert statement
int count = statement.executeUpdate("INSERT INTO Employee(FIRST_NAME, LAST_NAME, DEPARTMENT) "
+ "values('John', 'Trudaue', 'IT')");
System.out.println("Number of records Inserted " + count);
// update statement
count = statement.executeUpdate("UPDATE Employee SET DEPARTMENT = 'Finance' where id = 15");
System.out.println("Number of records Updated " + count);
//delete statement
count = statement.executeUpdate("Delete from Employee where id = 11");
System.out.println("Number of records Deleted " + count);
/** executeQuery method **/
// Executing Query
ResultSet rs = statement.executeQuery("Select * from Employee");
while(rs.next()){
System.out.println("id: " + rs.getInt("id") +
" First Name: " + rs.getString("FIRST_NAME") +
" Last Name: " + rs.getString("LAST_NAME")+
" Dept: " + rs.getString("DEPARTMENT"));
}
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(connection != null){
//close connection
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

