日常總結

任智華666發表於2017-05-04

連結資料庫

package Day0504;


import java.sql.*;


public class JDBCTest {

public static void main(String[] args){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/myschool";
String user = "root";
String password = "hbtt";
// 1、載入驅動
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("成功載入驅動");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
// 2、建立連線
conn = DriverManager.getConnection(url,user,password);

Statement stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT id,stuName, password, mobile , email, address FROM student");
System.out.println("ID\t姓名\t密碼\t手機號\t\te-mail\t\t住址");
while(rs.next()){
int a = rs.getInt("id");
String b = rs.getString("stuName");
String c = rs.getString("password");
String d = rs.getString("mobile");
String e = rs.getString("e-mail");
String f = rs.getString("address");
System.out.println(a+"\t"+b+"\t"+c+"\t"+d+"\t"+e+"\t"+f);
}

} catch (SQLException e) {
e.printStackTrace();
} finally {
// 4、關閉ResultSet、Statement和資料庫連線
try {
if (null != rs) {
rs.close();
}
if (null != pstmt) {
pstmt.close();
}
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

}

實體類特徵

屬性一般使用private修飾

提供pbulic修飾的getter/setter方法

實體類提供無參構造方法,根據業務提供有參構造

實現Java.io.Serializable介面,支援序列化機制


相關文章