JDBC中的元数据——2.参数元数据

package metadata;

import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import util.SQLUtil;

/**
 * 参数元数据:
 * 		
 * @author mzy
 *
 */
public class Demo02 {
	public static void main(String[] args) throws Exception {
		// easyUse();
		
		// insert();
		
		// update();
	}

	private static void update() {
		SQLUtil.update("update student set name=?, gender=? where id=?", new Object[]{"Lily", "男", 3});
	}

	private static void insert() {
		SQLUtil.update("insert into student(id, name, gender, score, birth) values (?, ?, ?, ?, ?)", 
				new Object[]{3, "lucy", "女", 90, "2018-05-04"});
	}

	private static void easyUse() throws Exception {
		DataSource ds = new ComboPooledDataSource();
		Connection conn = ds.getConnection();
		
		String sql = "insert into student(id, name, gender, score, birth) values(?, ?, ?, ?, ?)";
		
		// 预编译sql
		PreparedStatement stmt = conn.prepareStatement(sql);
		
		// 参数赋值
		/*
		stmt.setInt(1, 1);
		stmt.setString(2, "mzy");
		stmt.setString(3, "男");
		stmt.setDouble(4, 99);
		stmt.setString(5, "2017-05-04");
		
		int i = stmt.executeUpdate();
		System.out.println(i+"行受到影响!");
		*/
		// 知道预编译的sql有几个参数
		// 得到参数元数据
		ParameterMetaData metaData = stmt.getParameterMetaData();
		
		// 得到sql中有几个参数
		int count = metaData.getParameterCount();
		System.out.println(count);
		Object[] values = new Object[]{2, "stu", "女", 100, "2018-05-04"};
		// 有了参数元数据之后,就可以换一种方式进行赋值了
		for(int i=0; i<count; i++) {
			stmt.setObject(i+1, values[i]);
		}
		stmt.executeUpdate();
		System.out.println("插入成功!");
	}
}

其中部分已经封装到了SQLUtil中,请点击

 

posted @ 2018-05-12 11:54  五彩世界  阅读(121)  评论(0编辑  收藏  举报