Statement接口代表静态SQL语句,它用于使用Java程序创建和执行通用SQL语句。
您可以使用连接接口的createStatement()方法创建此接口的对象。通过调用此方法来创建一条语句,如下所示。
Statement stmt = null; try { stmt = conn.createStatement( ); . . . } catch (SQLException e) { . . . } finally { . . . }
一旦你创建了Statement对象可以使用的execute方法之一,即执行它execute()
,executeUpdate()
和,executeQuery()
。
execute():此方法用于执行SQL DDL语句,它返回一个布尔值,指定可以检索ResultSet对象的天气。
executeUpdate():此方法用于执行诸如插入,更新,删除之类的语句。它返回一个整数值,表示受影响的行数。
executeQuery():此方法用于执行返回表格数据的语句(示例SELECT语句)。它返回ResultSet类的对象。
以下JDBC应用程序演示了如何创建和执行语句。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class StatementExample { public static void main(String args[]) throws SQLException { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获得连接 String mysqlUrl = "jdbc:mysql://localhost/testdb"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建语句 Statement stmt = con.createStatement(); //执行语句 String createTable = "CREATE TABLE Employee(“ + "Name VARCHAR(255), " + "Salary INT NOT NULL, " + "Location VARCHAR(255))"; boolean bool = stmt.execute(createTable); String insertData = "INSERT INTO Employee(" + "Name, Salary, Location) VALUES " + "('Amit', 30000, 'Hyderabad'), " + "('Kalyan', 40000, 'Vishakhapatnam'), " + "('Renuka', 50000, 'Delhi'), " + "('Archana', 15000, 'Mumbai')"; int i = stmt.executeUpdate(insertData); System.out.println("Rows inserted: "+i); ResultSet rs = stmt.executeQuery("Select *from Employee"); while(rs.next()) { System.out.print("Name: "+rs.getString("Name")+", "); System.out.print("Salary: "+rs.getInt("Salary")+", "); System.out.print("City: "+rs.getString("Location")); System.out.println(); } } }
Connection established...... Rows inserted: 4 Name: Amit, Salary: 30000, City: Hyderabad Name: Kalyan, Salary: 40000, City: Vishakhapatnam Name: Renuka, Salary: 50000, City: Delhi Name: Archana, Salary: 15000, City: Mumbai