-
11.5更新
寫的時候用的是Statement,后來看到網(wǎng)上說Statement有SQL風險,用PreStatement更好。我沒想明白是怎么回事,在窗體中看不到什么SQL風險,后來在學習EE的時候,明白了什么是SQL注入。最后在框架學習中,
忘記寫Mysql打開的事兒了
在我的電腦右鍵管理 ->服務與應用程序 ->服務 ->打幾個m就出來啦
一直連接數(shù)據(jù)庫出錯,最后發(fā)先數(shù)據(jù)庫沒有打開。囧
數(shù)據(jù)庫連接在新手中一直是個小小坎。在java中數(shù)據(jù)庫連接寫的東西很多,但是真正達到我們想要的就只有那么一兩句話。
有一堆的code復用,這個時候就開始封裝。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection {
private DBConnection(){};
private static Connection connection;
static String classDriver = "com.mysql.jdbc.Driver";
static String username = "root";
static String password = "自己的密碼";
static String url ="jdbc:mysql://localhost:3306/MISDB" ;
public static Connection getConnection() throws SQLException {
try {
Class.forName(classDriver);
if (connection == null) {
connection = DriverManager.getConnection(url, username, password);
}else {
return connection;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
/**
* 關閉三個參數(shù)
* @param resultSet 記錄集
* @param statement 聲明
* @param connection 連接對象
* @throws SQLException
*/
public static void closeConnection(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {
if (resultSet !=null) {
resultSet.close();
}if (statement != null) {
statement.close();
}if (connection != null) {
connection.close();
}
}
/**
* @overRidden
* @param statement
* @param connection
* @throws SQLException
*/
public static void closeConnection(Statement statement, Connection connection) throws SQLException{
if (statement != null) {
statement.close();
}if (connection != null) {
connection.close();
}
}
}
PS:第一次用代碼縮進很差,抱拳了老鐵