ZBLOG

java获取服务器资源并写入数据库

要从服务器获取资源并将其写入数据库,可以使用Java中的网络编程和数据库连接技术。下面是一个简单的示例代码,演示了如何使用Java获取服务器资源并将其写入MySQL数据库:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class ServerResourceToDatabase {
    public static void main(String[] args) {
        String url = "http://example.com/resource"; // 服务器资源URL
        String databaseUrl = "jdbc:mysql://localhost:3306/mydatabase"; // 数据库连接URL
        String username = "your-username"; // 数据库用户名
        String password = "your-password"; // 数据库密码
        
        try {
            // 获取服务器资源
            URL serverUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) serverUrl.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            
            StringBuilder contentBuilder = new StringBuilder();
            String line;
            
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line);
                contentBuilder.append("\n");
            }
            
            reader.close();
            
            String resourceContent = contentBuilder.toString();

            // 连接到数据库
            Connection dbConnection = DriverManager.getConnection(databaseUrl, username, password);

            // 将资源内容写入数据库表
            String insertQuery = "INSERT INTO resources(content) VALUES (?)";
            
	    PreparedStatement preparedStatement = dbConnection.prepareStatement(insertQuery);
	    preparedStatement.setString(1, resourceContent);
	    
	    int rowsAffected = preparedStatement.executeUpdate();
	    
	    System.out.println("成功插入" + rowsAffected + "行数据.");

	    preparedStatement.close();
	    dbConnection.close();
	    
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
}

请确保已经导入合适的数据库驱动程序(如MySQL Connector/J),并替换示例代码中的URL、数据库连接URL、用户名和密码为实际值。同时,请根据你的数据库表结构进行相应的修改。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=11595

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?