JDBC操作数据库的步骤
注册驱动(通过Class.forName())
Class.forName("com.mysql.jdbc.Driver");
获得连接(通过DriverManager.getConnection())
String url = "jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8";
String user= "用户";
String password= "密码";
Connection connection = DriverManager.getConnection(url,user,password);
url(地址):jdbc:mysql://ip或主机:端口号/数据库名
写SQL语句
String sql = " ";
获得statement容器
Statement statement = connection.createStatement();
执行SQL语句,获得结果集(resultSet )
ResultSet resultSet = statement.executeQuery(sql);
处理结果集
while(resultSet.next()){
int id = resultSet.getInt(1);
String name = resultSet.getString("class_name");
int num = resultSet.getInt("class_num");
System.out.println(id+"-"+name+"-"+num);
}
关闭资源
finally {
try {
try{
if(resultSet != null){
resultSet.close();
}
}finally {
try{
if(statement != null){
statement.close();
}
}finally {
try{
if(connection != null){
connection.close();
}
}finally {
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
注意:倒着释放资源
原因:防止空指针
finally继续关闭其他资源