You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
zhky/src/main/java/com/zky/util/jdbc/JDBCUtilsExample.java

55 lines
1.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.zky.util.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class JDBCUtilsExample {
/**
* @param args
*/
public static void main(String[] args) {
Connection conn = null;
try {
//例子1 查询a=ta and b=1
//直接传递参数"ta",new Integer(1)
String sql = "SELECT * FROM tab_test WHERE a=? and b = ?";
List list = (List) JDBCUtils.query(conn,sql, "ta",new Integer(1),new ListResultSetHandler());
//或者 将参数作为数组传入
list = (List) JDBCUtils.query(conn,sql, new Object[]{"tttt",new Integer(1)},
new ListResultSetHandler());
//例子2
sql = "update tab_test set a=? where b=?";
JDBCUtils.update(conn,sql,"12121",new Integer(2005));
//或者
JDBCUtils.update(conn,sql,new Object[]{"12121",new Integer(2005)});
conn.commit();
//例子3使用一个匿名类来直接处理ResultSet
//注意外部变量要在匿名类内使用必须申明成final的
//申明成final的变量不能放在等号左边使用呵呵。
final StringBuffer curDate = new StringBuffer("") ;
sql = "select date_format(now(),'%Y-%m-%d') from dual";
JDBCUtils.query(conn,sql,new ResultSetHandler(){
public Object handle(ResultSet rs) throws SQLException{
while(rs.next()){
curDate.append(rs.getString(1));
}
return null;
}
}
);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.close(conn);
}
}
}