①方法executeQuery
用于产生单个结果集的语句,例如 SELECT 语句。 被使用最多的执行 SQL 语句的方法是 executeQuery。这个方法被用来执行 SELECT 语句,它几乎是使用最多的 SQL 语句。
例:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/student", "vane", "920514");//建立连接
PreparedStatement pst= conn.prepareStatement("INSERT INTO user(username,password1) VALUES (?,?)");//执行语句,返回PreparedStatement
pst.setString(1, Username);
pst.setString(2, Password);
pst.executeUpdate();
②方法executeUpdate
用于执行 INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句。
例如 CREATE TABLE 和 DROP TABLE。INSERT、UPDATE 或 DELETE 语句的效果是修改表中零行或多行中的一列或多列。
executeUpdate 的返回值是一个整数,指示受影响的行数(即更新计数)。对于 CREATE TABLE 或 DROP TABLE 等不操作行的语句,executeUpdate 的返回值总为零。
使用executeUpdate方法是因为在 createTableCoffees 中的 SQL 语句是 DDL (数据定义语言)语句。
创建表,改变表,删除表都是 DDL 语句的例子,要用 executeUpdate 方法来执行。
你也可以从它的名字里看出,方法 executeUpdate 也被用于执行更新表 SQL 语句。实际上,相对于创建表来说,executeUpdate 用于更新表的时间更多,因为表只需要创建一次,但经常被更新。
例:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "vane", "920514"); //建立连接
Statement sql_statement = con.createStatement(); //创建对象实例
ResultSet result = sql_statement.executeQuery("select * from student"); //执行语句,返回ResultSet对象
while (result.next())
{
int number = result.getInt("id");
String name = result.getString("name");
String mathScore = result.getString("math");
//取得数据库中的数据
System.out.println(" " + number + " " + name + " " + mathScore);
}