操作数据库的可以简单分为五个步骤
贾琏欲执事

贾 : 加载JDBC驱动程序
//加载MySql的驱动类
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace();
}
琏:连接数据库
//jdbc.properties 写在外面的方式
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///mybatis
db.username=root
db.password=admin
String url = "jdbc:mysql://localhost:test"; //连接url
String username = "root"; //账号
String password = "root"; //密码
try {
//连接数据库
Connection con = DriverManager.getConnection(url, username, password);
} catch (SQLException se) {
System.out.println("数据库连接失败!");
se.printStackTrace();
}
欲:查询语句
执:执行SQL语句
事:关闭事务
if (rs != null) { // 关闭记录集
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) { // 关闭声明
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) { // 关闭连接对象
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
版权声明:本文为wj6060原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。