一、什么是PreparedStatement
参阅Java API文档,我们可以知道,PreparedStatement是Statement的子接口(如图所示),表示预编译的 SQL 语句的对象,SQL 语句被预编译并存储在PreparedStatement
对象中。然后可以使用此对象多次高效地执行该语句。
二、通过PreparedStatement获取在运行命令行中执行的参数,将参数插入到某张数据表中
相关的实验过程,包括在预先创建程序所需数据库、创建所需数据表格、在开发环境中加载驱动程序包等,可参考前一篇文章《JDBC连接MySQL数据库及示例》(
前往该文章)
具体代码如下:
- package com.serein.jdbc;
-
- import java.sql.*;
-
- public class preparedStatemetTest {
-
- public static void main(String[] args) {
-
-
- if(args.length != 7) {
- System.out.println("Parameter Error! Please Input Again!");
- System.exit(-1);
- }
-
-
- String name = args[0];
- int age = 0;
- try {
- age = Integer.parseInt(args[1]);
- } catch (NumberFormatException e) {
- System.out.println("Parameter Error! Age should be Number Format!");
- System.exit(-1);
- }
-
- String sex = args[2];
- String address = args[3];
- String depart = args[4];
-
- int worklen = 0;
- try {
- worklen = Integer.parseInt(args[5]);
- } catch (NumberFormatException e) {
- System.out.println("Parameter Error! Worklen should be Number Format!");
- System.exit(-1);
- }
-
- int wage = 0;
- try {
- wage = Integer.parseInt(args[6]);
- } catch (NumberFormatException e) {
- System.out.println("Parameter Error! Wage should be Number Format!");
- System.exit(-1);
- }
-
-
- PreparedStatement pstmt = null;
-
- Connection conn = null;
-
-
- try {
-
- Class.forName("com.mysql.jdbc.Driver");
-
-
-
- conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myuser", "root", "root");
-
-
- pstmt = conn.prepareStatement("INSERT INTO staff(name, age, sex,address, depart, worklen,wage) VALUES (?, ?, ?, ?, ?, ?, ?)");
-
-
- pstmt.setString(1, name);
- pstmt.setInt(2, age);
- pstmt.setString(3, sex);
- pstmt.setString(4,address );
- pstmt.setString(5, depart);
- pstmt.setInt(6, worklen);
- pstmt.setInt(7, wage);
- pstmt.executeUpdate();
-
-
- System.out.print("成功插入一条数据记录!");
-
-
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
-
-
- } catch (SQLException e) {
- e.printStackTrace();
-
- } finally {
- try {
- if(pstmt != null) {
- pstmt.close();
- pstmt = null;
- }
- if(conn != null) {
- conn.close();
- conn = null;
- }
-
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }
编写好代码之后,要进行带参数运行程序,方法如下:
其中输入的参数为(可参考进行修改):
SereinChan
25
M
Guangzhou
Engine
3
5000
查看Console控制台,"成功插入一条数据记录!":
查看MySQL数据库,进行确认:
成功完成!
转自:http://blog.csdn.net/cxwen78/article/details/6868941
JDBC进阶之PreparedStatement执行SQL语句(MySQL)
原文:http://www.cnblogs.com/azhqiang/p/4036726.html