JDBC开发:模板式开发
1 加载驱动java连接数据库的jar包
2 获取数据库连接对象-〉地址,端口号3306,用户名密码 方案名
3 通过连接对象获取数据库操作对象
4 定义SQL语句 mysql用户名:root 密码:root
5 执行SQL语句(a 增加,修改,删除,返回结果为0或者非0 b查询返回结果是一个记录集合)
6 如果是查询,就遍历记录集合获取每个数据
7 关闭操作对象,返回连接对象
public static void main(String[] args) {
try { Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) { e.printStackTrace();
}
String url="jdbc:mysql://127.0.0.1:3306/mysql";
String user="root";
String password="root"; Connection conn=null;
Statement sta=null;
String sql="select * from user"; ResultSet set=null;
try { conn=DriverManager.getConnection(url, user, password); sta=conn.createStatement(); set=sta.executeQuery(sql);
while(set.next()){ String host=set.getString("host"); String username=set.getString(2); System.out.println(host+"..."+username);
} return;
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(set !=null){
try {
set.close();
} catch (SQLException e) { e.printStackTrace();
}
}
if(sta !=null){
try {
sta.close();
} catch (SQLException e) { e.printStackTrace();
}
}
if(conn !=null){
try {
conn.close();
} catch (SQLException e) { e.printStackTrace();
}
}
}