Java数据库连接与查询
时间:2021-07-01 10:21:17
帮助过:24人阅读
static void main(String[] args)
throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver"
);
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动类!"
);
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/exe_course"
;
String userName = "root"
;
String password = "123456"
;
try (Connection connection =
DriverManager.getConnection(url, userName, password)) {
System.out.println("数据库链接成功!"
);
try (Statement statement =
connection.createStatement()) {
String command = "insert into a_dept(name) values(‘1‘),(‘2‘)"
;
int count =
statement.executeUpdate(command);
System.out.println("受影响行数:" +
count);
String selectSql = "select * from a_dept"
;
try (ResultSet resultSet =
statement.executeQuery(selectSql)) {
while (resultSet.next()) {
System.out.println(resultSet.getInt("id"
));
System.out.println(resultSet.getString("name"
));
}
}
}
}
}
上面代码使用了try的两种用法,在需要释放资源的时候比较推荐使用第二种用法,这种方式会在使用结束之后自动关闭资源。
下面是运行结果:
Java数据库连接与查询
标签:password span ext lex http sele date 关闭数据库 from