Mysql数据库:java对象的存入和查询

首先说明下我们实验的条件:

数据库中的表:books ,字段id(int) book(Blob二进制流)

连接方式:JDBC

定义一个简单的连接数据库的类:

public class DataBase{
	public static final String Driver = "com.mysql.jdbc.Driver";
	public static final String url = "jdbc:mysql://localhost:3306/books";
	public static final String user = "root";
	public static final String password = "root";

	static {
		try {
			Class.forName(Driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public static Connection getConnection() throws SQLException{
		Connection conn = null;
		conn = DriverManager.getConnection(url,user,password);
		return conn;
	}
}


其次,定义测试类,我们使用ArrayList对象来实验,为了方便我们将异常进行抛出

class Test{
    public static void main(String[] args) throw Exception{
		ArrayList<String> al = new ArrayLIst<String>();
		al.add("1");
		al.add("2");
		al.add("3");
		//先进行数据的保存
		Connection conn = DataBase.getConnection();
		PreparedStatement pstmt = con.prepareStatement("insert into books values(1,?)");//想数据库中插入第一组数据
		pstmt.setObject(1,al);
		int time = pstmt.executeUpdate();//执行操作
		System.out.println(time+"插入完成");//提示插入完成
		pstmt.close();
		//再进行数据的提出
		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery("select book from books where id=1");
		if(rs.next()){
			ObjectInputStream oips = new ObjectInputStream(rs.getBinaryStream(1));
			//从rs中得到对象的流,如果直接从rs.getObject(1)得到的对象是无法直接转化为下面的对象的。
			ArrayList<String> obb = (ArrayList<String>)oips.readObject();//从流中读取对象
			System.out.println(obb.get(2));//输出对象中指定的数据
			oips.close();
		}
		rs.close();
		stmt.close();               
		con.close();
    }
}


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WJL_MGQS

本不富裕的收入,还得买服务器

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值