JDBC代码,DBUtil工具类提取测试

package com.biubiubiu.DBUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
/**
 * JDBC工具类测试
 * @author 11142
 *
 */
public class DB {
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public DB() {
	}

	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/1234", "root", "111111");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static void closeConn(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static PreparedStatement getPStmt(Connection conn, String sql) {
		PreparedStatement pstmt = null;
		try {
			pstmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return pstmt;
	}

	public static void closeStmt(Statement stmt) {
		try {
			if (stmt != null) {
				stmt.close();
				stmt = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static ResultSet executeQuery(Statement stmt, String sql) {
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	public static void closeRs(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 重载
	 * @param conn
	 * @param sql
	 * @return
	 */
	public static ResultSet executeQuery(Connection conn, String sql) {
		ResultSet rs = null;
		try {
			rs = conn.createStatement().executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	/**
	 * 插入数据测试
	 * @param data
	 * @throws SQLException 
	 */
	public static void showInfo(Object[] data) throws SQLException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		conn = DB.getConn();
		String sql = "insert into resources value (?,?,?,?,?,?)"; 
		pstmt = DB.getPStmt(conn, sql);
		pstmt.setString(1, (String)data[0]);
		pstmt.setString(2, (String)data[1]);
		pstmt.setString(3, (String)data[2]);
		pstmt.setString(4, (String)data[3]);
		pstmt.setTimestamp(5, (Timestamp)data[4]);
		pstmt.setString(6, (String)data[5]);
		pstmt.executeUpdate();
		DB.closeStmt(pstmt);
		DB.closeConn(conn);
	}
	
	public static void main(String[] args) {
		DB db = new DB();
		Object[] data = {"1","2","3","4",new Timestamp(1211156),"6"};
		try {
			db.showInfo(data);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

发布了108 篇原创文章 · 获赞 39 · 访问量 9358

猜你喜欢

转载自blog.csdn.net/qq_40246175/article/details/102926430
今日推荐