通过jdbc连接数据库
1、导入相关数据库的jar包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.7</version>
</dependency>
2、代码编写
2.1、查询
由于个人感觉在写随笔的时候,代码中简单的步骤添加try catch
会看起来不清晰,故没有添加。在实际中还是需要的。
public static void main( String[] args ) throws ClassNotFoundException, SQLException {
// 数据库连接地址
String url = "jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf-8";
String user = "root";
String password = "123456";
// 1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2、获取连接
Connection connection = DriverManager.getConnection(url, user, password);
// 3、编写SQL语句
String sql = "SELECT * FROM `ssmbuild`.`books`";
// 4、创建prepareStatement对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 5、使用prepareStatement对象执行SQL语句
ResultSet resultSet = preparedStatement.executeQuery();
// 6、遍历返回的结果集
while (resultSet.next()){
// 根据数据库创建对应的实体类!
Book book = new Book();
// 把查询到的结果封装到实体类!
book.setBookID(resultSet.getInt("bookID"));
book.setBookName(resultSet.getString("bookName"));
book.setBookCounts(resultSet.getInt("bookCounts"));
book.setDetail(resultSet.getString("detail"));
System.out.println(book.toString());
}
// 7、关闭资源,先开后关
resultSet.close();
preparedStatement.close();
connection.close();
}
2.2、增加
public static void main( String[] args ) throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf-8";
String user = "root";
String password = "123456";
// 1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2、获取连接
Connection connection = DriverManager.getConnection(url, user, password);
// 3、编写SQL语句
String sql = "INSERT INTO `ssmbuild`.`books` (`bookName`, `bookCounts`, `detail`) VALUES (?, ?, ?)";
// 4、创建prepareStatement对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 预编译对象,我们需要把?号替换
preparedStatement.setString(1,"C");
preparedStatement.setInt(2,20);
preparedStatement.setString(3,"从零开始");
// 5、使用prepareStatement对象执行SQL语句
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("数据插入成功!");
}else {
System.out.println("失败!");
}
// 6、关闭资源,先开后关
preparedStatement.close();
connection.close();
}
// 增删改都一样,换一下SQL语句就可以!
“学习是一个不断抄袭、模仿、练习、创新的过程”