JDBCUtils:
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
static {
try {
Properties pro = new Properties();
pro.load(new FileReader(("src/JDBC.properties")));
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
public static void close(ResultSet rs,Statement stmt,Connection conn){
if( rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if( stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if( conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
JDBC.properties:
url=jdbc:mysql://localhost:3306/text?serverTimezone=UTC
user=root
password=123456
driver=com.mysql.cj.jdbc.Driver

課程設計鏈接mysql例子:
public void getselcF(){
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;
SelectCourse selectCourse;
ArrayList<SelectCourse> fr =new ArrayList<>();
try {
connection=JDBCUtils.getConnection();
String sql ="select * from studcourse";
statement=connection.createStatement();
resultSet=statement.executeQuery(sql);
while(resultSet.next()){
String num=resultSet.getString("學號");
String name=resultSet.getString("姓名");
String courseNum=resultSet.getString("課程號");
String courseName=resultSet.getString("課程名");
String opSemester=resultSet.getString("開課學期");
String selectFlag=resultSet.getString("退選標志");
selectCourse =new SelectCourse(num,name,courseNum,courseName,opSemester,selectFlag);
fr.add(selectCourse);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/78647.html
標籤:其他
