欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDBC连接数据库的通用工具类

程序员文章站 2022-06-21 14:50:05
...
package com.sxt.utils;

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

public class JdbcUtils {
	//数据库用户名
		private static final String USERNAME = "root";
		//数据库密码
		private static final String PASSWORD = "root";
		//驱动信息 
		private static final String DRIVER = "com.mysql.jdbc.Driver";
		//数据库地址
		private static final String URL = "jdbc:mysql://localhost:3306/datetableName?useUnicode=true&characterEncoding=UTF-8";
		private static Connection connection;
		private static PreparedStatement pstmt;
		private static ResultSet resultSet;
		static{
			try {
				Class.forName("com.mysql.jdbc.Driver");
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		public static Connection getConnection(){
			try {
				
				connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return connection;
		}
		public static void closeConnection(Connection connection,PreparedStatement pstmt,ResultSet resultSet){
			try {
				if(connection!=null){
					connection.close();
				}
				if(pstmt!=null){
					pstmt.close();
				}
				if(resultSet!=null){
					resultSet.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
}

 

相关标签: 工具代码