eclipse读取mysql数据库_Eclipse通过JDBC连接MySQL数据库的步骤(最原始的几个步骤)

java可以兼容目前市面上所有类型的数据库,主要是因为提供了两个接口,一个用于连接目标数据库,一个用于向数据库中传输SQL命令。

Connection接口——连接目标数据库;

Statement  接口——向目标数据传送SQL命令;

这里主要介绍Eclipse连接MySqL数据库的流程(MySQL以5.7版本为例):

1、导入JDBC驱动包

Class.forName("com.mysql.jdbc.Driver");

2、获取连接对象(连接目标数据库)

Connection connection = Drivermanager.getConnection("jdbc : mysql : // localhost : 3306 / 数据库名" , user , password );

注意:不同类型的数据库的连接方法不同,这里连接MySQL数据库,使用的是本机3306端口。

3、获取Statement对象(向目标数据库发送SQL命令)

Statement statement = connection.createStatement( );

3.1编辑命令:

String sql = "DELETE FROM table WHERE id = 3"; //删除table表中id为3的这一条数据

3.2发送命令:

int num = statement.executeUpdate( sql );

注意:由于对数据的操作类型不同,statement调用的方法也不同,在具体使用时需要注意,例如在对数据进行更新操作(增、删、改)时,调用executeUpdate( ),而在执行查询操作时应使用executeQuerry( )

4、 关闭资源

connection.close( );

statement.close( );

在对数据库进行数据操作完成后,需要进行资源关闭的操作。

**在进行查询操作的时候,因为需要接收数据库中返回的数据信息,需要创建 ResultSet结果集来接收信息,最后可通过遍历的方式查看数据。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,将图片存储到MySQL数据库中需要将图片转换为二进制流格式,并将其存储在BLOB类型的字段中。以下是一个示例代码片段,演示如何将图片存储到MySQL数据库中: ```java // 读取图片 File file = new File("path/to/image.jpg"); FileInputStream input = new FileInputStream(file); byte[] imageBytes = new byte[(int)file.length()]; input.read(imageBytes); input.close(); // 建立数据库连接 Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); // 存储图片 PreparedStatement statement = connection.prepareStatement("INSERT INTO images (name, image) VALUES (?, ?)"); statement.setString(1, file.getName()); statement.setBytes(2, imageBytes); statement.executeUpdate(); statement.close(); connection.close(); ``` 接下来,演示如何从MySQL数据库中取出图片。 ```java // 建立数据库连接 Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); // 从数据库中取出图片 PreparedStatement statement = connection.prepareStatement("SELECT image FROM images WHERE name = ?"); statement.setString(1, "image.jpg"); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { byte[] imageBytes = resultSet.getBytes(1); // 将二进制流写入文件 FileOutputStream output = new FileOutputStream("path/to/output.jpg"); output.write(imageBytes); output.close(); } resultSet.close(); statement.close(); connection.close(); ``` 以上代码片段演示了如何从数据库中取出图片,并将其写入文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值