在不使用框架的情况下,写的简单的jdbc 调用通用方法
package com.panie.dao;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class localdao
{
// 设置驱动变量(jdbc的驱动程序放在WEB-INF下的lib目录下)
static String sDBDriver = "com.mysql.jdbc.Driver";
// 创建连接,数据库名landingbj,连接mysql的用户名是root,密码为空(如果你的mysql有用户名和密码请填上你的用户名和密码)
static String sConnStr = "jdbc:mysql://127.0.0.1:3306/landingbj?user=root&password=yourpwd";
public static Connection getConn() {
Connection conn = null;
try {
Class.forName(sDBDriver);// 加载驱动
// 获得连接
conn = DriverManager.getConnection(sConnStr);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public int insertTable(String tablename,Object object)
{
Field fields [] = object.getClass().getDeclaredFields();
StringBuffer sb = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
sb.append("insert into ").append(tablename).append("(");
sb2.append(" values(");
List<Object> valueList = new ArrayList<Object>();
for(int j = 0 ; j < fields.length; j++)
{
fields[j].setAccessible(true);
try
{
String fieldName = fields[j].getName();
String field = fieldName;
int index = 0;
for(int i = 0; i < fieldName.length(); i++)
{
char c = fieldName.charAt(i);
if (Character.isUpperCase(c))
{
index = fieldName.indexOf(c,index);
field = fieldName.substring(0,index)+"_"+fieldName.substring(index);
}
}
if(fields[j].get(object)!=null)
{
sb.append(field).append(",");
sb2.append("?").append(",");
valueList.add(fields[j].get(object));
}
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sb.deleteCharAt(sb.length()-1).append(")");
sb2.deleteCharAt(sb2.length()-1).append(")");
String sql = sb.toString()+sb2.toString();
Object[] params = valueList.toArray();
return executeUpdate(sql,params);
}
public int executeUpdate(String sql, Object[] params)
{
PreparedStatement ps = null;
Connection conn = getConn();
int result = 0;
try
{
ps = conn.prepareStatement(sql);// 获得预处理对象
// 判断SQL语句中是否有问号占位符
if (params != null && params.length != 0)
{
// 如果存在问号占位符,在给问号占位符设置值
for (int i = 0; i < params.length; i++)
{
ps.setObject(i + 1, params[i]);
}
}
// 执行增、删、改SQL语句
result = ps.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
close(null,ps,conn);
}
return result;
}
public static void close(ResultSet rs,PreparedStatement ps,Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}