您的位置:首页 > 数据库 > MySQL

JDBC进阶之PreparedStatement执行SQL语句(MySQL)

2014-10-20 11:05 513 查看
一、什么是PreparedStatement
参阅Java API文档,我们可以知道,PreparedStatement是Statement的子接口(如图所示),表示预编译的 SQL 语句的对象,SQL 语句被预编译并存储在
PreparedStatement
对象中。然后可以使用此对象多次高效地执行该语句。




二、通过PreparedStatement获取在运行命令行中执行的参数,将参数插入到某张数据表中
相关的实验过程,包括在预先创建程序所需数据库、创建所需数据表格、在开发环境中加载驱动程序包等,可参考前一篇文章《JDBC连接MySQL数据库及示例》(前往该文章
具体代码如下:

[java] view plaincopy

package com.serein.jdbc;

import java.sql.*;

public class preparedStatemetTest {

public static void main(String[] args) {

//检查命令行中是否够7个参数

if(args.length != 7) {

System.out.println("Parameter Error! Please Input Again!");

System.exit(-1);

}

//程序获取运行栈里的7个参数值

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对象

PreparedStatement pstmt = null;

//创建连接对象

Connection conn = null;

//连接数据库,并插入数据

try {

//加载MySQL驱动实例,提供了两种方法,是等价的

Class.forName("com.mysql.jdbc.Driver");

//new oracle.jdbc.driver.OracleDriver();

//建立连接

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myuser", "root", "root");

//使用PreparedStatement对象里来构建并执行SQL语句,7个问号代表7个字段预先要保留的值

pstmt = conn.prepareStatement("INSERT INTO staff(name, age, sex,address, depart, worklen,wage) VALUES (?, ?, ?, ?, ?, ?, ?)");

//通过PreparedStatement对象里的set方法去设置插入的具体数值

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();

//捕获SQL语句执行失败异常

} catch (SQLException e) {

e.printStackTrace();

//恢复变量初始值

} finally {

try {

if(pstmt != null) {

pstmt.close();

pstmt = null;

}

if(conn != null) {

conn.close();

conn = null;

}

//捕获SQL异常

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

编写好代码之后,要进行带参数运行程序,方法如下:








其中输入的参数为(可参考进行修改):
SereinChan
25
M
Guangzhou
Engine
3
5000

查看Console控制台,"成功插入一条数据记录!":





查看MySQL数据库,进行确认:





成功完成!

转自:http://blog.csdn.net/cxwen78/article/details/6868941
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: