1.使用JDBC的步骤:
public static void main(String[] args) {
//初始化驱动
String url="jdbc:mysql://localhost:3306/how2j";
String name ="root";
String psw="admin";
String driverName="com.mysql.cj.jdbc.Driver";//最新版本的驱动
try {
//1.加载数据驱动
Class.forName(driverName);
//2.建立数据库连接
Connection c = DriverManager.getConnection(url, name, psw);
//3.执行sql语句(insert,update,delete,select)
Statement s = c.createStatement();
String sql = "insert into hero values(null,"+"'ォスセ'"+","+224.0f+","+60+")";
//4.执行insert,update,delete
s.executeUpdate(sql);
//关闭对象(必须是这个顺序)
s.close();
c.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
**
2.关闭方式:
(1)直接关闭,但是必须先关闭Statement对象,再关闭Connnection对象.如上代码中那样。
( 2 ) 可以放在finally中关闭,但是必须先关闭Statement对象,再关闭Connnection对象。
finally {
// 数据库的连接时有限资源,相关操作结束后,养成关闭数据库的好习惯
// 先关闭Statement
if (s != null)
try {
s.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 后关闭Connection
if (c != null)
try {
c.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
。**
(3)用更简单而规范一点的方式,是用try-with-resource的方式自动关闭连接,因为Connection和Statement都实现了AutoCloseable接口
String url="jdbc:mysql://localhost:3306/how2j?user=root&password=admin";
String driverName="com.mysql.cj.jdbc.Driver";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try (
Connection c = DriverManager.getConnection(url);
Statement s = c.createStatement();
)
{
String sql = "insert into hero values(null," + "'九尾狐'" + "," + 500.0f + "," + 120 + ")";
s.execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}