JDBC 中的 Statement 是什么?
jdbcjava 8mysql更新于 2024/12/2 21:32:17
Statement 接口表示静态 SQL 语句,它用于使用 Java 程序创建和执行通用 SQL 语句。
创建语句
您可以使用 connection 接口的 createStatement() 方法创建此接口的对象。通过调用此方法创建语句,如下所示。
Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
执行 Statement 对象
创建 Statement 对象后,您可以使用以下执行方法之一执行它,即 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 {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/testdb";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Executing the statement
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
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

