maven專案連線MySQL(使用原生的jdbc)
//依賴
<dependency>
<groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
jdbc.properties 內容:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=123456
package com.cxb.shiro;
import java.io.IOException;
import java.util.Properties;
/**
* 獲取資原始檔的util
* @author 81046
*
*/
public class PropertiesUtil {
static Properties properties = new Properties();
public PropertiesUtil() {
}
public static boolean loadFile(String fileName){
try {
properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static String getPropertyValue(String key){
return properties.getProperty(key);
}
}
package com.cxb.shiro;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcUtils {
//通過上面的工具就可以獲取到properties檔案中的鍵值從而可以載入驅動 獲取連結 從而 可以增刪改查
private static Connection conn = null;
public static Connection getConn(){
PropertiesUtil.loadFile("jdbc.properties");
String driver = PropertiesUtil.getPropertyValue("driver");
String url = PropertiesUtil.getPropertyValue("url");
String username = PropertiesUtil.getPropertyValue("username");
String password = PropertiesUtil.getPropertyValue("password");
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
close();
}
return conn;
}
public static void close(){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 通過使用者名稱到資料庫中獲取憑證密碼
* @param userName
* @return
*/
private static String getPasswordByUserName(String userName) {
//SQL語句
String sql = "select password from users where username = " +"'" + userName+"'";
Connection conn = JdbcUtils.getConn();
Statement stmt=null;
ResultSet ret = null;
String password=null;
try {
stmt = conn.createStatement();
//執行語句,得到結果集
ret = stmt.executeQuery(sql);
while (ret.next()) {
//這裡只查詢的密碼
password = ret.getString(1);
}
ret.close();
conn.close();//關閉連線
} catch (SQLException e1) {
e1.printStackTrace();
}
return password;
}