JavaWeb JDBC連線MySql資料庫小專案
阿新 • • 發佈:2019-02-14
環境:eclipse,mysql
1. 在mysql裡面建表test
2. 匯入連結mysql的jar包
3. 建立DataAccess的工具類,在這個類裡面執行資料庫連結操作,返回Connection這個物件。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * test 資料庫連線操作 * @author Administrator * / public class DataAccess { private static final String driver="com.mysql.jdbc.Driver"; private static final String url="jdbc:mysql://localhost:3306/test ?useUnicode=true&characterEncoding=UTF-8&useSSL=true"; private static final String username="root"; private static final String passwork="2315806986"; private static Connection conn=null; static{ try{ //載入驅動 Class.forName(driver); }catch(Exception ex){ ex.printStackTrace(); } } public static Connection getConnection() throws Exception{ if(conn==null){ //連線資料庫 conn=DriverManager.getConnection(url, username, passwork); return conn; } //判斷資料庫連線是否成功 if(conn!=null){ System.out.println("連線正常"); }else{ System.out.println("連線異常"); } return conn; } public static Boolean closeConnection(){ if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return true; }
}
4. User的實體類,test資料庫裡面的test表有關欄位組成這個類,便於對資料進行操作
public class User { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }
}
5. 查詢的操作類,裡面包括一個quaryAll()的函式,查詢資料庫test表的所有資料,返回ArrayList < User > ;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; public class UserDAO { /** * 查詢資料庫裡面所有的資料 * @return */ public static ArrayList<User> quaryAll(){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; ArrayList<User> list = new ArrayList<User>(); try { conn = DataAccess.getConnection(); String sql = "select * from test;"; stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { User item = new User(); item.setAge(rs.getInt("age")); item.setName(rs.getString("name")); item.setId(rs.getInt("id")); list.add(item); } return list; } catch (Exception ex) { ex.printStackTrace(); return null; } finally { if (rs != null) { try { rs.close(); rs = null; } catch (Exception e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); stmt = null; } catch (Exception e) { e.printStackTrace(); } } } } }
6. 測試的test類,主函式,打印出所查資料。
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<User> userList = UserDAO.quaryAll();
for(User user : userList){
System.out.println("查詢出來的id是:"+user.getId());
System.out.println("查詢出來的名字是:"+user.getName());
System.out.println("查詢出來的年齡是:"+user.getAge());
}
}
}