首页 > 代码库 > jdbc总结

jdbc总结

Connection con = null;
PreparedStatement sta = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("反射加载驱动程序错误!");
}
try {
con = DriverManager
.getConnection(
"jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",
"root", "");
} catch (SQLException e) {
System.out.println("获取数据库链接错误!");
}

String sql = "SELECT * FROM user WHERE username=?";
try {
sta = con.prepareStatement(sql);
sta.setString(1, "王五");
} catch (SQLException e1) {
System.out.println("预编译语句错误!");
}
try {
rs = sta.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("id") + " "
+ rs.getString("username"));

}
} catch (SQLException e1) {
System.out.println("结果集错误!");

} finally {

if (rs != null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (sta != null)
try {
sta.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

jdbc总结