java中PreparedStatement用法和HelloWorld例子
PreparedStatement的HelloWorld程序
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
除了Statement以外,Sun公司還提供了另外一個(gè)工具PreparedStatement,它們兩個(gè)的效率比較,我們下一節(jié)再說(shuō),本節(jié)我們只講 helloworld。PreparedStatement的用法就是:PreparedStatement中的SQL語(yǔ)句,可有一個(gè)或多個(gè)參數(shù)。每個(gè)參數(shù)用一個(gè)問(wèn)號(hào)(“?”)來(lái)占位。之后每個(gè)問(wèn)號(hào)的值必須通過(guò)適當(dāng)?shù)膕etXXX方法來(lái)提供。
例:2.1.1
import java.io.IOException;
public class TestMark_to_win {
public static void main(String[] args) throws java.sql.SQLException,
ClassNotFoundException, IOException {
java.sql.Connection connection = null;
java.sql.PreparedStatement pstmt;
Class.forName("com.mysql.jdbc.Driver");
connection = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "1234");
pstmt = connection.prepareStatement("UPDATE login SET name = ? WHERE id = ?");
pstmt.setString(1, "qqq");
pstmt.setString(2, "1");
/*缺了下面這句,id為1的這一列更新不了了 */
pstmt.executeUpdate();
pstmt.setString(1, "qqqq");
pstmt.setString(2, "2");
pstmt.executeUpdate();
pstmt.close();
System.out.println("ok");
connection.close();
}
}