JDBC进阶之PreparedStatement执行SQL语句(MySQL)
PreparedStatement
对象中。然后可以使用此对象多次高效地执行该语句。- 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();
- }
- }
- }
- }
25
M
Guangzhou
Engine
3
5000
查看Console控制台,"成功插入一条数据记录!":
查看MySQL数据库,进行确认:
成功完成!
转自:http://blog.csdn.net/cxwen78/article/details/6868941
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。