JDBC主要作用
JDBC的主要作用是对数据库里的数据的处理
我们先根据步骤连接数据库
1.加载MySql的驱动
Class.forName("com.mysql.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://:3306/test?user=root&password=123");
2.获取数据库的对象
Connection conn= DriverManager.getConnection("jdbc:mysql://:3306/test?user=root&password=123");
3.调用SQL语句
String sql="update student set age=18 where id=1";
4.获得SQL语句
Statement stat=conn.createStatement();
5.执行SQL语句
int count=stat.executeUpdate(sql);
6.根据返回值处理结果
System.out.println(count);
7.释放资源
stat.close();
conn.close();
改造后代码
private static void Test2() {
Statement stat=null;
Connection conn=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://:3306/test?user=root&password=123");
String sql="select password from account where username='zhangsan'";
stat=conn.createStatement();
rs=stat.executeQuery(sql);
while(rs.next()){
String password=rs.getString("password");
System.out.println(password);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try{
if(stat!=null)
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
try{
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static void Test2() {
Statement stat=null;
Connection conn=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://:3306/test?user=root&password=123");
String sql="select password from account where username='zhangsan'";
stat=conn.createStatement();
rs=stat.executeQuery(sql);
while(rs.next()){
String password=rs.getString("password");
System.out.println(password);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try{
if(stat!=null)
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
try{
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
改造后的代码增加了异常处理和代码的完整性,更加完善,大家可以学着改造。