java database connection
依靠底层驱动 实现统一规范
1. 加载数据库驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
2. 建立连接
String username = "root";
String password = "password" ;
String url = "jdbc:mysql://localhost:3306/test";
Connection conn = DriverManager.getConnection(url,username,password);
3. 创建语句对象 并 发送语句
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
4. 从ResultSet中取数据
while(rs.next()) { //ResultSet默认指针是指到0
String userID = rs.getInt(1);
String userName = rs.getString(2);
String password = rs.getString(3);
System.out.println(userID+" "+userName+" "+password) ;
}
5. 断开数据库连接
rs.close();
st.close();
conn.close();