jdbc DBUtil

package com.example.demo.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
	private static Connection conn = null;
	private static PreparedStatement st = null;
	private static ResultSet rs = null;

	private static Connection getConnection(String sql){
		//1.注册加载jdbc数据库驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			//2.得到连接对象 Connection
			String username = "root";
			String password = "root";
			String url = "jdbc:mysql://127.0.0.1:3306/shp?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowMultiQueries=true";
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static void insertOrupdate(String sql){
		Connection conn = getConnection(sql);
		try {
			//不能防止sql注入
			//Statement statement = con.createStatement();
			//3.创建 Statement对象
			st = conn.prepareStatement(sql);
			//4.执行sql
			st.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static ResultSet query(String sql){
		Connection conn = getConnection(sql);
		try {
			st = conn.prepareStatement(sql);
			rs = st.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

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

}
ResultSet rs = DBUtil.query("select * from t_user");
		while (rs.next()){
			System.out.println(rs.getString("wx_nickname"));
		}
		DBUtil.closeAll();

 

Published 48 original articles · won praise 1 · views 2842

Guess you like

Origin blog.csdn.net/Forest24/article/details/89675393