需要导入的包:
- mysql-connector-java-5.1.37-bin.jar
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
导包:
mysql-connector-java-5.1.37-bin.jar
*/
public class JdbcUtils {
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String URL = "jdbc:mysql://localhost:3306/newdatabase";
private static String USER = "root";
private static String PASSWORD = "1234"; static {
try {
Class.forName(DRIVER);
} catch (Exception e) {
throw new RuntimeException(e);
}
} /**
* 获得连接
*
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
return connection;
} /**
* 释放资源
*
* @param connection
* @param statement
* @param resultSet
*/
public static void closeResouce(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (statement != null) { try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
} }